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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,64 @@ dependencies {

Refer to our [SDK documentation](https://docs.geteppo.com/sdks/server-sdks/java/) for how to install and use the SDK.

## Upgrading from 5.x to 6.0.0

6.0.0 moves the `cloud.eppo:sdk-common-jvm` API dependency from 3.13.2 to 4.0.3.
Common 4.0.3 adds `cloud.eppo:eppo-sdk-framework` 0.1.3 as an API dependency.
Recompile code that you built against 5.x.

If your code uses common SDK types directly:

- DTOs moved from `cloud.eppo.ufc.dto` to `cloud.eppo.api.dto`. Except for the
enums, they are now interfaces. Replace constructors such as
`new FlagConfig(...)` with `new FlagConfig.Default(...)`. `BanditAttributeCoefficients` has no `Default`
implementation; supply an implementation if you construct it directly.
- `cloud.eppo.ufc.dto.adapters.EppoModule` and `EppoValueDeserializer` did not
move. The other adapters are no longer public.
- `cloud.eppo.model.ShardRange` is now `cloud.eppo.api.dto.ShardRange`.
- `Configuration.builder(byte[])` and `builder(byte[], boolean)` were removed. Use
`Configuration.builder(new JacksonConfigurationParser().parseFlagConfig(bytes))`,
or `new Configuration.Builder(flagConfigResponse, isConfigObfuscated)` to set the
obfuscation flag yourself.
- `Configuration.serializeFlagConfigToBytes()`,
`Configuration.serializeBanditParamsToBytes()` and
`Attributes.serializeNonNullAttributesToJSONString()` were removed.
`cloud.eppo.exception.InvalidApiKeyException` was also removed.
- `cloud.eppo.EppoHttpClient` was removed. To supply your own HTTP client,
implement `cloud.eppo.http.EppoConfigurationClient` and pass it to
`EppoClient.builder(sdkKey).configurationClient(...)`. The default is
`OkHttpEppoClient`; pass `new OkHttpEppoClient(okHttpClient)` to reuse your own
OkHttp settings. To point tests at a stub server, use `apiBaseUrl(...)`.

Behaviour changes:

- With `isGracefulMode(false)`, `getJSONAssignment()`, `getJSONStringAssignment()`
and their `*Details()` variants throw when the assigned variation is not valid
JSON. 5.x returned the default (for `getJSONAssignment()`, only a non-null
default). Graceful mode still returns the default.
- Once the client saves a configuration that came with an ETag, polls send
`If-None-Match`. When the server answers 304 Not Modified, the client keeps its
configuration and `onConfigurationChange` does not fire. In 5.x it fired after
every successful poll.

New: `get*AssignmentDetails()` and `getBanditActionDetails()` return evaluation
details with the value.

The SDK no longer brings Ehcache and its supporting libraries transitively.
If your application uses Ehcache directly, declare its dependency explicitly.

Common 4.0.2 changes how the client handles bandit failures:

- A failed bandit fetch no longer blocks flag updates. The client applies the new
flags, keeps its loaded bandit models, and retries the bandits on the next poll.
- When bandit evaluation fails, for example because the models are not loaded yet,
graceful mode (the default) makes `getBanditAction` return the default value with
a null action, and `getBanditActionDetails` reports evaluation code `BANDIT_ERROR`.
Common 3.13.2 returned the bandit variation. The assignment logger has already
recorded the flag's bandit variation for that call, so the logged variation can
differ from the value your code receives. With graceful mode disabled, both
methods throw, as in 5.x.

## Contributing

Java 8 is required to locally compile the SDK.
Expand Down Expand Up @@ -48,7 +106,8 @@ Once you have the prerequisites, follow the steps below to release a new version

If you would like to live on the bleeding edge, you can try running against a snapshot build. Keep in mind that snapshots
represent the most recent changes on master and may contain bugs.
Snapshots are published automatically after each push to `main` branch.
Snapshots are published automatically after each push to the `main` branch while `build.gradle` has a
`-SNAPSHOT` version.

### build.gradle:

Expand All @@ -58,6 +117,6 @@ repositories {
}

dependencies {
implementation 'cloud.eppo:eppo-server-sdk:6.0.0-SNAPSHOT'
implementation 'cloud.eppo:eppo-server-sdk:X.Y.Z-SNAPSHOT'
}
```
9 changes: 4 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ java {
}

group = 'cloud.eppo'
version = '6.0.0-SNAPSHOT'
version = '6.0.0'
Comment thread
typotter marked this conversation as resolved.
Resolved
ext.isReleaseVersion = !version.endsWith("SNAPSHOT")

import org.apache.tools.ant.filters.ReplaceTokens
Expand All @@ -41,15 +41,14 @@ repositories {
}

dependencies {
api 'cloud.eppo:sdk-common-jvm:4.0.0-SNAPSHOT'
api 'cloud.eppo:sdk-common-jvm:4.0.3'

implementation 'com.github.zafarkhaja:java-semver:0.10.2'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.22.3'
implementation 'org.ehcache:ehcache:3.11.1'
implementation 'org.slf4j:slf4j-api:2.0.17'
implementation 'org.jetbrains:annotations:26.1.0'

testImplementation 'cloud.eppo:eppo-sdk-framework:0.1.0-SNAPSHOT:tests'
// Use the framework version resolved by common so tests match the runtime.
testImplementation 'cloud.eppo:eppo-sdk-framework::tests'
testImplementation 'org.slf4j:slf4j-simple:2.0.17'
testImplementation platform('org.junit:junit-bom:5.14.4')
testImplementation 'org.junit.jupiter:junit-jupiter'
Expand Down
39 changes: 36 additions & 3 deletions src/main/java/cloud/eppo/EppoClient.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package cloud.eppo;

import cloud.eppo.api.Attributes;
import cloud.eppo.api.Configuration;
import cloud.eppo.api.IAssignmentCache;
import cloud.eppo.cache.ExpiringInMemoryAssignmentCache;
import cloud.eppo.cache.LRUInMemoryAssignmentCache;
import cloud.eppo.http.EppoConfigurationClient;
import cloud.eppo.logging.AssignmentLogger;
import cloud.eppo.logging.BanditLogger;
import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -46,7 +48,8 @@ private EppoClient(
@Nullable BanditLogger banditLogger,
boolean isGracefulMode,
@Nullable IAssignmentCache assignmentCache,
@Nullable IAssignmentCache banditAssignmentCache) {
@Nullable IAssignmentCache banditAssignmentCache,
@Nullable EppoConfigurationClient configurationClient) {
super(
sdkKey,
sdkName,
Expand All @@ -62,7 +65,24 @@ private EppoClient(
assignmentCache,
banditAssignmentCache,
new JacksonConfigurationParser(),
new OkHttpEppoClient());
configurationClient != null ? configurationClient : new OkHttpEppoClient());
}

// Preserve concrete method descriptors used by callers compiled against server 5.x.
@Override
public Configuration getConfiguration() {
return super.getConfiguration();
}

@Override
public JsonNode getJSONAssignment(String flagKey, String subjectKey, JsonNode defaultValue) {
return super.getJSONAssignment(flagKey, subjectKey, defaultValue);
}

@Override
public JsonNode getJSONAssignment(
String flagKey, String subjectKey, Attributes subjectAttributes, JsonNode defaultValue) {
return super.getJSONAssignment(flagKey, subjectKey, subjectAttributes, defaultValue);
}

/**
Expand All @@ -84,6 +104,7 @@ public static class Builder {
private long pollingIntervalMs = DEFAULT_POLLING_INTERVAL_MS;
private String apiBaseUrl = null;
@Nullable private Consumer<Configuration> configChangeCallback;
@Nullable private EppoConfigurationClient configurationClient;

// Assignment and bandit caching on by default. To disable, call
// `builder.assignmentCache(null).banditAssignmentCache(null);`
Expand Down Expand Up @@ -169,6 +190,17 @@ public Builder onConfigurationChange(Consumer<Configuration> configChangeCallbac
return this;
}

/**
* Supplies the HTTP client that fetches configurations, for example to add custom networking,
* authentication or logging. The default is an {@link OkHttpEppoClient}; to reuse your own
* OkHttp settings, pass {@code new OkHttpEppoClient(okHttpClient)}. See {@link
* EppoConfigurationClient} for the contract.
*/
public Builder configurationClient(@NotNull EppoConfigurationClient configurationClient) {
this.configurationClient = configurationClient;
return this;
}

public EppoClient buildAndInit() {
AppDetails appDetails = AppDetails.getInstance();
String sdkName = appDetails.getName();
Expand Down Expand Up @@ -197,7 +229,8 @@ public EppoClient buildAndInit() {
banditLogger,
isGracefulMode,
assignmentCache,
banditAssignmentCache);
banditAssignmentCache,
configurationClient);

if (configChangeCallback != null) {
instance.onConfigurationChange(configChangeCallback);
Expand Down
156 changes: 156 additions & 0 deletions src/test/java/cloud/eppo/EppoClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static cloud.eppo.helpers.AssignmentTestCase.parseTestCaseFile;
import static cloud.eppo.helpers.AssignmentTestCase.runTestCase;
import static cloud.eppo.helpers.AssignmentTestCase.runTestCaseWithDetails;
import static cloud.eppo.helpers.BanditTestCase.parseBanditTestCaseFile;
import static cloud.eppo.helpers.BanditTestCase.runBanditTestCase;
import static org.junit.jupiter.api.Assertions.*;
Expand Down Expand Up @@ -122,6 +123,14 @@ public void testUnobfuscatedAssignments(File testFile) {
runTestCase(testCase, eppoClient);
}

@ParameterizedTest
@MethodSource("getAssignmentTestData")
public void testUnobfuscatedAssignmentsWithDetails(File testFile) {
AssignmentTestCase testCase = parseTestCaseFile(testFile);
EppoClient eppoClient = initClient(DUMMY_FLAG_API_KEY);
runTestCaseWithDetails(testCase, eppoClient);
}

private static Stream<Arguments> getAssignmentTestData() {
return AssignmentTestCase.getAssignmentTestData();
}
Expand Down Expand Up @@ -306,6 +315,88 @@ public void testConfigurationChangeListener() {
assertEquals(2, received.size());
}

// The first bandit fetch fails. The flags still apply, bandit flags return the default with
// BANDIT_ERROR, and the next poll sends no ETag, retries the bandits and serves the bandit.
@Test
public void testBanditFetchFailureAppliesFlagsAndRetriesOnNextPoll() {
String flags = readConfig("src/test/resources/shared/ufc/bandit-flags-v1.json");
String models = readConfig("src/test/resources/shared/ufc/bandit-models-v1.json");
mockServer.resetAll();
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/config.*"))
.withHeader("If-None-Match", WireMock.equalTo("\"v1\""))
.willReturn(WireMock.aResponse().withStatus(304)));
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/config.*"))
.withHeader("If-None-Match", WireMock.absent())
.willReturn(WireMock.okJson(flags).withHeader("ETag", "\"v1\"")));
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/bandits.*"))
.inScenario("bandits")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(WireMock.serverError())
.willSetStateTo("up"));
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/bandits.*"))
.inScenario("bandits")
.whenScenarioStateIs("up")
.willReturn(WireMock.okJson(models)));
mockAssignmentLogger = mock(AssignmentLogger.class);
mockBanditLogger = mock(BanditLogger.class);
EppoClient client =
EppoClient.builder(DUMMY_BANDIT_API_KEY)
.apiBaseUrl(TEST_HOST)
.assignmentLogger(mockAssignmentLogger)
.banditLogger(mockBanditLogger)
.pollingIntervalMs(0)
.forceReinitialize(true)
.buildAndInit();
Attributes bob = new Attributes();
bob.put("age", 25);
bob.put("country", "USA");
BanditActions actions = new BanditActions();
actions.put("nike", new Attributes());
actions.put("adidas", new Attributes());

assertNotNull(client.getConfiguration().getFlag("banner_bandit_flag"));
BanditResult fallback =
client.getBanditAction("banner_bandit_flag", "bob", bob, actions, "control");
assertEquals("control", fallback.getVariation());
assertNull(fallback.getAction());
assertEquals(
cloud.eppo.api.FlagEvaluationCode.BANDIT_ERROR,
client
.getBanditActionDetails("banner_bandit_flag", "bob", bob, actions, "control")
.getEvaluationDetails()
.getFlagEvaluationCode());
verify(mockBanditLogger, never()).logBanditAssignment(any());

client.loadConfiguration();
BanditResult recovered =
client.getBanditAction("banner_bandit_flag", "bob", bob, actions, "control");
assertEquals("banner_bandit", recovered.getVariation());
assertNotNull(recovered.getAction());
}

@Test
public void testCustomConfigurationClientIsUsed() {
OkHttpEppoClient delegate = new OkHttpEppoClient();
List<String> requestedPaths = new ArrayList<>();
EppoClient eppoClient =
EppoClient.builder(DUMMY_FLAG_API_KEY)
.apiBaseUrl(TEST_HOST)
.configurationClient(
request -> {
requestedPaths.add(request.getResourcePath());
return delegate.execute(request);
})
.forceReinitialize(true)
.buildAndInit();

assertFalse(requestedPaths.isEmpty());
assertNotNull(eppoClient.getConfiguration().getFlag("numeric_flag"));
}

public static void mockHttpError() {
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/config.*"))
Expand Down Expand Up @@ -418,4 +509,69 @@ private void initBuggyClient() {
+ " }\n"
+ "}")
.getBytes();

@Test
public void testNotModifiedDoesNotNotifyConfigurationChange() {
mockServer.resetAll();
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/config.*"))
.willReturn(WireMock.okJson(new String(BOOL_FLAG_CONFIG)).withHeader("ETag", "v1")));
mockServer.stubFor(
WireMock.get(WireMock.urlMatching(".*flag-config/v1/config.*"))
.withHeader("If-None-Match", WireMock.equalTo("v1"))
.willReturn(WireMock.aResponse().withStatus(304)));
List<Configuration> received = new ArrayList<>();
EppoClient client =
EppoClient.builder(DUMMY_FLAG_API_KEY)
.apiBaseUrl(TEST_HOST)
.pollingIntervalMs(0)
.forceReinitialize(true)
.onConfigurationChange(received::add)
.isGracefulMode(false)
.buildAndInit();
Configuration initial = client.getConfiguration();
client.loadConfiguration();
assertEquals(1, received.size());
assertSame(initial, client.getConfiguration());
mockServer.verify(
1,
WireMock.getRequestedFor(WireMock.urlMatching(".*flag-config/v1/config.*"))
.withHeader("If-None-Match", WireMock.equalTo("v1")));
}

@Test
public void testDocumentedConfigurationBuilderMigration() throws Exception {
byte[] bytes = readConfig("src/test/resources/shared/ufc/flags-v1.json").getBytes("UTF-8");
cloud.eppo.api.dto.FlagConfigResponse response =
new JacksonConfigurationParser().parseFlagConfig(bytes);
Configuration inferred = Configuration.builder(response).build();
Configuration explicit = new Configuration.Builder(response, false).build();
assertNotNull(inferred.getFlag("numeric_flag"));
assertNotNull(explicit.getFlag("numeric_flag"));
}

@Test
public void testKeepsVersion5MethodDescriptors() throws NoSuchMethodException {
assertEquals(
Configuration.class, EppoClient.class.getMethod("getConfiguration").getReturnType());
assertEquals(
com.fasterxml.jackson.databind.JsonNode.class,
EppoClient.class
.getMethod(
"getJSONAssignment",
String.class,
String.class,
com.fasterxml.jackson.databind.JsonNode.class)
.getReturnType());
assertEquals(
com.fasterxml.jackson.databind.JsonNode.class,
EppoClient.class
.getMethod(
"getJSONAssignment",
String.class,
String.class,
cloud.eppo.api.Attributes.class,
com.fasterxml.jackson.databind.JsonNode.class)
.getReturnType());
}
}
Loading