-
Notifications
You must be signed in to change notification settings - Fork 23
feat: Reduce streaming DNS failures with stale-fallback DNS cache #323
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abelonogov-ld
wants to merge
6
commits into
main
Choose a base branch
from
andrey/dns-sdk34
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f990e9e
dns cache
abelonogov-ld 1cd1904
cap cache
abelonogov-ld ebd37ab
fix modifiable issue
abelonogov-ld 4c65601
Make cache for all
abelonogov-ld 443c6b3
fix eviction logic
abelonogov-ld 0a6a23e
Refactor eviction logic in CachingDns to use an explicit iterator for…
abelonogov-ld File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
113 changes: 113 additions & 0 deletions
113
launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/CachingDns.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| package com.launchdarkly.sdk.android; | ||
|
|
||
| import androidx.annotation.VisibleForTesting; | ||
|
|
||
| import com.launchdarkly.logging.LDLogger; | ||
|
|
||
| import java.net.InetAddress; | ||
| import java.net.UnknownHostException; | ||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| import okhttp3.Dns; | ||
|
|
||
| /** | ||
| * A DNS resolver that caches successful lookups and falls back to stale cache | ||
| * entries when a fresh resolution fails. This is particularly useful on mobile | ||
| * networks where DNS can be unreliable during network transitions. | ||
| * <p> | ||
| * Although Android API 34+ exposes {@code DnsOptions.StaleDnsOptions} in | ||
| * {@code DnsResolver}, OkHttp's {@code Dns.SYSTEM} uses | ||
| * {@code InetAddress.getAllByName} which does not opt into that mechanism. | ||
| * This class is therefore used on all API levels. | ||
| * <p> | ||
| * Instances of this class are thread-safe and designed to be shared across | ||
| * multiple OkHttpClient instances so that the cache persists even when the | ||
| * HTTP client is recreated (e.g. on EventSource reconnections). | ||
| */ | ||
| final class CachingDns implements Dns { | ||
|
|
||
| @VisibleForTesting | ||
| static final long DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 minutes | ||
| @VisibleForTesting | ||
| static final int MAX_ENTRIES = 30; | ||
|
|
||
| private final Dns delegate; | ||
| private final long ttlMs; | ||
| private final LDLogger logger; | ||
| private final ConcurrentHashMap<String, CacheEntry> cache = new ConcurrentHashMap<>(); | ||
|
|
||
| static final class CacheEntry { | ||
| final List<InetAddress> addresses; | ||
| final long expiresAtMs; | ||
|
|
||
| CacheEntry(List<InetAddress> addresses, long expiresAtMs) { | ||
| this.addresses = Collections.unmodifiableList(new ArrayList<>(addresses)); | ||
| this.expiresAtMs = expiresAtMs; | ||
| } | ||
|
|
||
| boolean isExpired(long nowMs) { | ||
| return nowMs >= expiresAtMs; | ||
| } | ||
| } | ||
|
|
||
| CachingDns(Dns delegate, long ttlMs, LDLogger logger) { | ||
| this.delegate = delegate; | ||
| this.ttlMs = ttlMs; | ||
| this.logger = logger; | ||
| } | ||
|
|
||
| CachingDns(LDLogger logger) { | ||
| this(Dns.SYSTEM, DEFAULT_TTL_MS, logger); | ||
| } | ||
|
|
||
| @Override | ||
| public List<InetAddress> lookup(String hostname) throws UnknownHostException { | ||
| long now = System.currentTimeMillis(); | ||
| CacheEntry entry = cache.get(hostname); | ||
|
|
||
| if (entry != null && !entry.isExpired(now)) { | ||
| return entry.addresses; | ||
| } | ||
|
|
||
| try { | ||
| List<InetAddress> addresses = delegate.lookup(hostname); | ||
| long afterLookup = System.currentTimeMillis(); | ||
| if (cache.size() >= MAX_ENTRIES) { | ||
| evictExpired(afterLookup); | ||
| } | ||
| cache.put(hostname, new CacheEntry(addresses, afterLookup + ttlMs)); | ||
| return addresses; | ||
| } catch (UnknownHostException e) { | ||
| if (entry != null) { | ||
| logger.warn( | ||
| "DNS lookup failed for {}, falling back to cached address (age {}ms)", | ||
| hostname, System.currentTimeMillis() - (entry.expiresAtMs - ttlMs) | ||
| ); | ||
| return entry.addresses; | ||
| } | ||
| throw e; | ||
| } | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| private void evictExpired(long now) { | ||
| java.util.Iterator<java.util.Map.Entry<String, CacheEntry>> it = cache.entrySet().iterator(); | ||
| while (it.hasNext()) { | ||
| if (it.next().getValue().isExpired(now)) { | ||
| it.remove(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| int cacheSize() { | ||
| return cache.size(); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| CacheEntry getCacheEntry(String hostname) { | ||
| return cache.get(hostname); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
171 changes: 171 additions & 0 deletions
171
...hdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/CachingDnsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| package com.launchdarkly.sdk.android; | ||
|
|
||
| import static org.junit.Assert.assertEquals; | ||
|
|
||
| import com.launchdarkly.logging.LDLogger; | ||
|
|
||
| import org.junit.Test; | ||
|
|
||
| import java.net.InetAddress; | ||
| import java.net.UnknownHostException; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| import okhttp3.Dns; | ||
|
|
||
| public class CachingDnsTest { | ||
|
|
||
| private static final LDLogger logger = LDLogger.none(); | ||
|
|
||
| private static Dns counting(List<InetAddress> result, AtomicInteger counter) { | ||
| return hostname -> { | ||
| counter.incrementAndGet(); | ||
| return result; | ||
| }; | ||
| } | ||
|
|
||
| private static Dns failing() { | ||
| return hostname -> { | ||
| throw new UnknownHostException("simulated DNS failure for " + hostname); | ||
| }; | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsFreshResultFromDelegate() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> expected = Collections.singletonList(addr); | ||
| AtomicInteger lookups = new AtomicInteger(); | ||
| CachingDns dns = new CachingDns(counting(expected, lookups), 60_000, logger); | ||
|
|
||
| List<InetAddress> result = dns.lookup("example.com"); | ||
| assertEquals(expected, result); | ||
| assertEquals(1, lookups.get()); | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsCachedResultWithinTtl() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> expected = Collections.singletonList(addr); | ||
| AtomicInteger lookups = new AtomicInteger(); | ||
| CachingDns dns = new CachingDns(counting(expected, lookups), 60_000, logger); | ||
|
|
||
| dns.lookup("example.com"); | ||
| List<InetAddress> result = dns.lookup("example.com"); | ||
|
|
||
| assertEquals(expected, result); | ||
| assertEquals(1, lookups.get()); | ||
| } | ||
|
|
||
| @Test | ||
| public void refreshesAfterTtlExpires() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> expected = Collections.singletonList(addr); | ||
| AtomicInteger lookups = new AtomicInteger(); | ||
| CachingDns dns = new CachingDns(counting(expected, lookups), 0, logger); | ||
|
|
||
| dns.lookup("example.com"); | ||
| dns.lookup("example.com"); | ||
|
|
||
| assertEquals(2, lookups.get()); | ||
| } | ||
|
|
||
| @Test | ||
| public void fallsBackToStaleCacheOnFailure() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> cached = Collections.singletonList(addr); | ||
|
|
||
| AtomicInteger lookups = new AtomicInteger(); | ||
| Dns flaky = hostname -> { | ||
| if (lookups.incrementAndGet() == 1) { | ||
| return cached; | ||
| } | ||
| throw new UnknownHostException("simulated failure"); | ||
| }; | ||
|
|
||
| CachingDns dns = new CachingDns(flaky, 0, logger); | ||
| dns.lookup("example.com"); | ||
|
|
||
| List<InetAddress> result = dns.lookup("example.com"); | ||
| assertEquals(cached, result); | ||
| } | ||
|
|
||
| @Test(expected = UnknownHostException.class) | ||
| public void throwsWhenDelegateFailsAndNoCacheExists() throws Exception { | ||
| CachingDns dns = new CachingDns(failing(), 60_000, logger); | ||
| dns.lookup("no-such-host.invalid"); | ||
| } | ||
|
|
||
| @Test | ||
| public void cachesPerHostname() throws Exception { | ||
| InetAddress addr1 = InetAddress.getByName("10.0.0.1"); | ||
| InetAddress addr2 = InetAddress.getByName("10.0.0.2"); | ||
| List<InetAddress> list1 = Collections.singletonList(addr1); | ||
| List<InetAddress> list2 = Collections.singletonList(addr2); | ||
|
|
||
| AtomicInteger lookups = new AtomicInteger(); | ||
| Dns delegate = hostname -> { | ||
| lookups.incrementAndGet(); | ||
| return hostname.equals("a.example.com") ? list1 : list2; | ||
| }; | ||
| CachingDns dns = new CachingDns(delegate, 60_000, logger); | ||
|
|
||
| assertEquals(list1, dns.lookup("a.example.com")); | ||
| assertEquals(list2, dns.lookup("b.example.com")); | ||
| assertEquals(2, lookups.get()); | ||
|
|
||
| assertEquals(list1, dns.lookup("a.example.com")); | ||
| assertEquals(list2, dns.lookup("b.example.com")); | ||
| assertEquals(2, lookups.get()); | ||
| } | ||
|
|
||
| @Test | ||
| public void evictsExpiredEntriesWhenCacheExceedsMax() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> addrs = Collections.singletonList(addr); | ||
| AtomicInteger lookups = new AtomicInteger(); | ||
|
|
||
| // TTL of 0 means every entry expires immediately | ||
| CachingDns dns = new CachingDns(counting(addrs, lookups), 0, logger); | ||
|
|
||
| // Fill beyond MAX_ENTRIES with distinct hostnames; each previous entry | ||
| // is already expired by the time the next lookup runs. | ||
| for (int i = 0; i <= CachingDns.MAX_ENTRIES; i++) { | ||
| dns.lookup("host-" + i + ".example.com"); | ||
| } | ||
|
|
||
| // The last put should have triggered eviction of all expired entries, | ||
| // leaving only the most recent (non-expired at the instant it was stored). | ||
| assertEquals(1, dns.cacheSize()); | ||
| } | ||
|
|
||
| @Test | ||
| public void retainsNonExpiredEntriesAcrossEviction() throws Exception { | ||
| InetAddress addr = InetAddress.getByName("127.0.0.1"); | ||
| List<InetAddress> addrs = Collections.singletonList(addr); | ||
| AtomicInteger lookups = new AtomicInteger(); | ||
|
|
||
| // Long TTL so nothing expires during the test | ||
| CachingDns dns = new CachingDns(counting(addrs, lookups), 600_000, logger); | ||
|
|
||
| for (int i = 0; i <= CachingDns.MAX_ENTRIES; i++) { | ||
| dns.lookup("host-" + i + ".example.com"); | ||
| } | ||
|
|
||
| // Nothing is expired, so eviction can't remove anything | ||
| assertEquals(CachingDns.MAX_ENTRIES + 1, dns.cacheSize()); | ||
| } | ||
|
|
||
| @Test | ||
| public void cacheEntryRecordsExpiration() { | ||
| InetAddress loopback = InetAddress.getLoopbackAddress(); | ||
| List<InetAddress> addrs = Collections.singletonList(loopback); | ||
|
|
||
| long now = System.currentTimeMillis(); | ||
| CachingDns.CacheEntry entry = new CachingDns.CacheEntry(addrs, now + 5000); | ||
|
|
||
| assertEquals(false, entry.isExpired(now)); | ||
| assertEquals(true, entry.isExpired(now + 5000)); | ||
| assertEquals(true, entry.isExpired(now + 6000)); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.