diff --git a/gradle.properties b/gradle.properties index e6b5417..3ff46e7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,2 @@ -version=10.1.0 +version=10.1.1 SONATYPE_CONNECT_TIMEOUT_SECONDS=120 \ No newline at end of file diff --git a/src/main/java/com/configcat/ConfigService.java b/src/main/java/com/configcat/ConfigService.java index 955e0a4..074696a 100644 --- a/src/main/java/com/configcat/ConfigService.java +++ b/src/main/java/com/configcat/ConfigService.java @@ -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()); } @@ -130,26 +130,31 @@ public CompletableFuture getSettings() { private CompletableFuture> 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; @@ -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()) { @@ -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()) diff --git a/src/main/java/com/configcat/Constants.java b/src/main/java/com/configcat/Constants.java index fbf303e..9da9c27 100644 --- a/src/main/java/com/configcat/Constants.java +++ b/src/main/java/com/configcat/Constants.java @@ -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"; diff --git a/src/main/java/com/configcat/Entry.java b/src/main/java/com/configcat/Entry.java index d3aa208..decafb0 100644 --- a/src/main/java/com/configcat/Entry.java +++ b/src/main/java/com/configcat/Entry.java @@ -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; @@ -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); diff --git a/src/test/java/com/configcat/AutoPollingTest.java b/src/test/java/com/configcat/AutoPollingTest.java index c7b9838..4ad9749 100644 --- a/src/test/java/com/configcat/AutoPollingTest.java +++ b/src/test/java/com/configcat/AutoPollingTest.java @@ -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(); + } } diff --git a/src/test/java/com/configcat/ConfigCatClientTest.java b/src/test/java/com/configcat/ConfigCatClientTest.java index a03feac..98adcfc 100644 --- a/src/test/java/com/configcat/ConfigCatClientTest.java +++ b/src/test/java/com/configcat/ConfigCatClientTest.java @@ -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'}}] } } }"; @@ -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 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(); diff --git a/src/test/java/com/configcat/EntrySerializationTest.java b/src/test/java/com/configcat/EntrySerializationTest.java index 1c33ed0..f4eedb6 100644 --- a/src/test/java/com/configcat/EntrySerializationTest.java +++ b/src/test/java/com/configcat/EntrySerializationTest.java @@ -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"))); diff --git a/src/test/java/com/configcat/Helpers.java b/src/test/java/com/configcat/Helpers.java index 7aa620f..4dd95c5 100644 --- a/src/test/java/com/configcat/Helpers.java +++ b/src/test/java/com/configcat/Helpers.java @@ -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(); } diff --git a/src/test/java/com/configcat/ManualPollingTest.java b/src/test/java/com/configcat/ManualPollingTest.java index d6cb501..fc26edf 100644 --- a/src/test/java/com/configcat/ManualPollingTest.java +++ b/src/test/java/com/configcat/ManualPollingTest.java @@ -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; @@ -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 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 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")));