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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
version=10.1.0
version=10.1.1
SONATYPE_CONNECT_TIMEOUT_SECONDS=120
30 changes: 18 additions & 12 deletions src/main/java/com/configcat/ConfigService.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public ConfigService(String sdkKey,
} else {
// Sync up with cache before reporting ready state
Entry fromCache = readCache();
if (!fromCache.isEmpty() && !fromCache.getETag().equals(cachedEntry.get().getETag())){
if (!fromCache.isEmpty() && !fromCache.getETag().equals(cachedEntry.get().getETag())) {
cachedEntry.set(fromCache);
configCatHooks.invokeOnConfigChanged(fromCache.getConfig().getEntries());
}
Expand Down Expand Up @@ -130,26 +130,31 @@ public CompletableFuture<SettingResult> getSettings() {
private CompletableFuture<Result<Entry, RefreshErrorCode>> fetchIfOlder(long threshold, boolean preferCached) {
// Sync up with the cache and use it when it's not expired.
Entry fromCache = readCache();
if (!fromCache.isEmpty() && !fromCache.getETag().equals(cachedEntry.get().getETag()) && fromCache.getFetchTime() > cachedEntry.get().getFetchTime()) {
Entry current = cachedEntry.get();
if (!fromCache.isEmpty() &&
(current.isEmpty() || (!fromCache.getETag().equals(current.getETag()) && fromCache.getFetchTime() > current.getFetchTime())) &&
cachedEntry.compareAndSet(current, fromCache)) {
configCatHooks.invokeOnConfigChanged(fromCache.getConfig().getEntries());
cachedEntry.set(fromCache);
}
current = cachedEntry.get();
// Cache isn't expired
if (cachedEntry.get().getFetchTime() > threshold) {
if (current.getFetchTime() > threshold) {
setInitialized();
return CompletableFuture.completedFuture(Result.success(cachedEntry.get(), RefreshErrorCode.NONE));
return CompletableFuture.completedFuture(Result.success(current, RefreshErrorCode.NONE));
}
// If we are in offline mode or the caller prefers cached values, do not initiate fetch.
if (offline.get() || preferCached) {
return CompletableFuture.completedFuture(Result.success(cachedEntry.get(), RefreshErrorCode.NONE));
setInitialized();
return CompletableFuture.completedFuture(Result.success(current, RefreshErrorCode.NONE));
}

lock.lock();
try {
if (runningTask == null) { // No fetch is running, initiate a new one.
runningTask = new CompletableFuture<>();
configFetcher.fetchAsync(cachedEntry.get().getETag())
.thenAccept(this::processResponse);
Entry finalCurrent = current;
configFetcher.fetchAsync(finalCurrent.getETag())
.thenAccept(response -> this.processResponse(response, finalCurrent));
}

return runningTask;
Expand Down Expand Up @@ -200,8 +205,7 @@ public boolean isOffline() {
return offline.get();
}

private void processResponse(FetchResponse response) {
Entry previousEntry = cachedEntry.get();
private void processResponse(FetchResponse response, Entry current) {
lock.lock();
try {
if (response.isFetched()) {
Expand All @@ -212,8 +216,10 @@ private void processResponse(FetchResponse response) {
completeRunningTask(Result.success(entry, RefreshErrorCode.NONE));
} else {
if (response.isFetchTimeUpdatable()) {
cachedEntry.set(previousEntry.withFetchTime(System.currentTimeMillis()));
writeCache(cachedEntry.get());
Entry updateEntry = current.withFetchTime(System.currentTimeMillis());
if (cachedEntry.compareAndSet(current, updateEntry)) {
writeCache(updateEntry);
}
}
completeRunningTask(response.isFailed()
? Result.error(response.error(), cachedEntry.get(), response.errorCode(), response.errorException())
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/configcat/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ private Constants() { /* prevent from instantiation*/ }
static final long DISTANT_PAST = 0;
static final String CONFIG_JSON_NAME = "config_v6.json";
static final String SERIALIZATION_FORMAT_VERSION = "v2";
static final String VERSION = "10.1.0";
static final String VERSION = "10.1.1";

static final String SDK_KEY_PROXY_PREFIX = "configcat-proxy/";
static final String SDK_KEY_PREFIX = "configcat-sdk-1";
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/configcat/Entry.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public Entry withFetchTime(long fetchTime) {
public boolean isExpired(long threshold) {
return fetchTime <= threshold ;
}

public Entry(Config config, String eTag, String configJson, long fetchTime) {
this.config = config;
this.eTag = eTag;
Expand Down Expand Up @@ -79,7 +80,7 @@ public static Entry fromString(String cacheValue) throws IllegalArgumentExceptio
}
String configJson = cacheValue.substring(eTagIndex + 1);
if (configJson.isEmpty()) {
throw new IllegalArgumentException("Empty config jsom value.");
throw new IllegalArgumentException("Empty config json value.");
}
try {
Config config = Utils.deserializeConfig(configJson);
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/com/configcat/AutoPollingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -330,5 +330,28 @@ void testInitWaitTimeIgnoredWhenCacheIsNotExpired() throws Exception {

configService.close();
}

@Test
void testInitWaitTimeReturnCached() throws Exception {
this.server.enqueue(new MockResponse().setResponseCode(200).setBody(String.format(TEST_JSON, "test1")).setBodyDelay(2, TimeUnit.SECONDS));

ConfigCache cache = new SingleValueCache(Helpers.cacheValueFromConfigJsonWithTime(String.format(TEST_JSON, "test"), Constants.DISTANT_PAST));

PollingMode pollingMode = PollingModes.autoPoll(60, 1);
ConfigFetcher fetcher = new ConfigFetcher(new OkHttpClient(),
logger,
"",
this.server.url("/").toString(),
false,
pollingMode.getPollingIdentifier());
ConfigService configService = new ConfigService("", fetcher, pollingMode, cache, logger, false, new ConfigCatHooks());

long start = System.currentTimeMillis();
assertEquals("test", configService.getSettings().get().settings().get("fakeKey").getSettingsValue().getStringValue());
long duration = System.currentTimeMillis() - start;
assertTrue(duration < 1500);

configService.close();
}
}

23 changes: 23 additions & 0 deletions src/test/java/com/configcat/ConfigCatClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

public class ConfigCatClientTest {
private static final String TEST_JSON = "{ p: { s: 'test-salt' }, f: { fakeKey: { t: 1, v: {s: 'fakeValue'}, s: 0, p: [] ,r: [] } } }";
private static final String TEST_JSON_FORMAT_VALUE = "{ p: { s: 'test-salt' }, f: { fakeKey: { t: 1, v: {s: %s}, s: 0, p: [] ,r: [] } } }";
private static final String TEST_JSON_MULTIPLE = "{ p: { s: 'test-salt' }, f: { key1: { t: 0, v: {b: true}, i: 'fakeId1', p: [] ,r: [] }, key2: { t: 0, v: {b: false}, i: 'fakeId2', p: [] ,r: [] } } }";
public static final String TEST_JSON_DEFAULT_USER = "{ p: { s: 'test-salt' }, 'f':{'fakeKey':{ t: 1, 'v': {s: 'defaultValue'},'i':'defaultId', r: [ {c: [ {u: { a: 'Identifier', c: 2, l: ['test1']}}],s: { v: {s: 'fakeValue1'},i: 'test1Id'}},{c: [{u: {a: 'Identifier', c: 2,l: ['test2']}}],s: { v: {s: 'fakeValue2'},i: 'test2Id'}}] } } }";
public static final String RULES_JSON = "{ p: { s: 'test-salt' }, f: { key: { t: 1, v: {s: 'def'}, t: 1, i: 'defVar', p: [] , r: [ {c: [ {u: { a: 'Identifier', c: 2, l: ['@test1.com']}}],s: { v: {s: 'fake1'},i: 'id1'}},{c: [{u: {a: 'Identifier', c: 2,l: ['@test2.com']}}],s: { v: {s: 'fake2'},i: 'id2'}}] } } }";
Expand Down Expand Up @@ -266,6 +267,28 @@ void getConfigurationReturnsPreviousCachedOnTimeout() throws IOException {
cl.close();
}

@Test
void testOlderExternalCacheEntryDoesNotReplaceNewerInMemoryEntry() throws IOException {
long now = System.currentTimeMillis();
String newer = Helpers.cacheValueFromConfigJsonWithTime(String.format(TEST_JSON_FORMAT_VALUE, "newer"), now);
String older = Helpers.cacheValueFromConfigJsonWithTime(String.format(TEST_JSON_FORMAT_VALUE, "older"), now - 60000);
SingleValueCache cache = new SingleValueCache(newer);

ConfigCatClient cl = ConfigCatClient.get(Helpers.SDK_KEY, options -> {
options.pollingMode(PollingModes.manualPoll());
options.cache(cache);
});

Map<String, Object> values = cl.getAllValues();
assertEquals("newer", values.get("fakeKey"));

cache.write("fakeCacheKey", older);
values = cl.getAllValues();
assertEquals("newer", values.get("fakeKey"));

cl.close();
}

@Test
void maxInitWaitTimeTest() throws IOException {
MockWebServer server = new MockWebServer();
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/com/configcat/EntrySerializationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ void deserializeInvalidJson() {
long currentTimeMillis = System.currentTimeMillis();
Exception assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis / 1000, "fakeTag", "")));

assertEquals("Empty config jsom value.", assertThrows.getMessage());
assertEquals("Empty config json value.", assertThrows.getMessage());

assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis / 1000, "fakeTag", "wrongjson")));

Expand Down
6 changes: 5 additions & 1 deletion src/test/java/com/configcat/Helpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ static String cacheValueFromConfigJsonWithTime(String json, long time) {
}

static String cacheValueFromConfigJsonWithEtag(String json, String etag) {
return cacheValueFromConfigJsonWithEtagAndTime(json, etag, System.currentTimeMillis());
}

static String cacheValueFromConfigJsonWithEtagAndTime(String json, String etag, long time) {
Config config = Utils.gson.fromJson(json, Config.class);
Entry entry = new Entry(config, etag, json, System.currentTimeMillis());
Entry entry = new Entry(config, etag, json, time);
return entry.getCacheString();
}

Expand Down
61 changes: 61 additions & 0 deletions src/test/java/com/configcat/ManualPollingTest.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package com.configcat;

import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -115,6 +120,62 @@ void testCache() throws InterruptedException, ExecutionException, IOException {
service.close();
}

@Test
void testNotModifiedDoesNotRefreshEntryReplacedDuringFetch() throws Exception {
assertResponseDoesNotRefreshEntryReplacedDuringFetch(304, RefreshErrorCode.NONE);
}

@Test
void testNonTransientErrorDoesNotRefreshEntryReplacedDuringFetch() throws Exception {
assertResponseDoesNotRefreshEntryReplacedDuringFetch(404, RefreshErrorCode.INVALID_SDK_KEY);
}

private void assertResponseDoesNotRefreshEntryReplacedDuringFetch(int status, RefreshErrorCode expectedErrorCode) throws Exception {
CompletableFuture<String> requestedETag = new CompletableFuture<>();
CountDownLatch allowResponse = new CountDownLatch(1);
this.server.setDispatcher(new Dispatcher() {
@NotNull
@Override
public MockResponse dispatch(@NotNull RecordedRequest request) throws InterruptedException {
requestedETag.complete(request.getHeader("If-None-Match"));
allowResponse.await(10, TimeUnit.SECONDS);
return new MockResponse().setResponseCode(status);
}
});

long now = System.currentTimeMillis();
String original = Helpers.cacheValueFromConfigJsonWithEtagAndTime(String.format(TEST_JSON, "original"), "original", now - 120000);
String replacement = Helpers.cacheValueFromConfigJsonWithEtagAndTime(String.format(TEST_JSON, "replacement"), "replacement", now - 60000);
SingleValueCache cache = new SingleValueCache(original);

PollingMode mode = PollingModes.manualPoll();
ConfigFetcher fetcher = new ConfigFetcher(new OkHttpClient.Builder().build(), logger, "", this.server.url("/").toString(), false, mode.getPollingIdentifier());
ConfigService service = new ConfigService("", fetcher, mode, cache, logger, false, new ConfigCatHooks());

try {
CompletableFuture<RefreshResult> refresh = service.refresh();
long replacementFetchTime = Entry.fromString(replacement).getFetchTime();

try {
assertEquals("original", requestedETag.get(5, TimeUnit.SECONDS));
cache.write("", replacement);
SettingResult settings = service.getSettings().get();
assertEquals("replacement", settings.settings().get("fakeKey").getSettingsValue().getStringValue());
assertEquals(replacementFetchTime, settings.fetchTime());
} finally {
allowResponse.countDown();
}

RefreshResult result = refresh.get(5, TimeUnit.SECONDS);
assertEquals(expectedErrorCode, result.errorCode());
assertEquals(expectedErrorCode == RefreshErrorCode.NONE, result.isSuccess());
assertEquals(replacementFetchTime, service.getSettings().get().fetchTime());
assertEquals(replacement, cache.read(""));
} finally {
service.close();
}
}

@Test
void testEmptyCacheDoesNotInitiateHTTP() throws InterruptedException, ExecutionException {
this.server.enqueue(new MockResponse().setResponseCode(200).setBody(String.format(TEST_JSON, "test")));
Expand Down