1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.resolver.dns;
17
18 import io.netty5.channel.EventLoop;
19 import io.netty5.util.AsciiString;
20
21 import java.util.List;
22
23 import static io.netty5.util.internal.ObjectUtil.checkPositive;
24 import static io.netty5.util.internal.ObjectUtil.checkPositiveOrZero;
25 import static java.util.Objects.requireNonNull;
26
27
28
29
30 public final class DefaultDnsCnameCache implements DnsCnameCache {
31 private final int minTtl;
32 private final int maxTtl;
33
34 private final Cache<String> cache = new Cache<>() {
35 @Override
36 protected boolean shouldReplaceAll(String entry) {
37
38 return true;
39 }
40
41 @Override
42 protected boolean equals(String entry, String otherEntry) {
43 return AsciiString.contentEqualsIgnoreCase(entry, otherEntry);
44 }
45 };
46
47
48
49
50 public DefaultDnsCnameCache() {
51 this(0, Cache.MAX_SUPPORTED_TTL_SECS);
52 }
53
54
55
56
57
58
59
60 public DefaultDnsCnameCache(int minTtl, int maxTtl) {
61 this.minTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositiveOrZero(minTtl, "minTtl"));
62 this.maxTtl = Math.min(Cache.MAX_SUPPORTED_TTL_SECS, checkPositive(maxTtl, "maxTtl"));
63 if (minTtl > maxTtl) {
64 throw new IllegalArgumentException(
65 "minTtl: " + minTtl + ", maxTtl: " + maxTtl + " (expected: 0 <= minTtl <= maxTtl)");
66 }
67 }
68
69 @SuppressWarnings("unchecked")
70 @Override
71 public String get(String hostname) {
72 requireNonNull(hostname, "hostname");
73 List<? extends String> cached = cache.get(hostname);
74 if (cached == null || cached.isEmpty()) {
75 return null;
76 }
77
78 return cached.get(0);
79 }
80
81 @Override
82 public void cache(String hostname, String cname, long originalTtl, EventLoop loop) {
83 requireNonNull(hostname, "hostname");
84 requireNonNull(cname, "cname");
85 requireNonNull(loop, "loop");
86 cache.cache(hostname, cname, Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)), loop);
87 }
88
89 @Override
90 public void clear() {
91 cache.clear();
92 }
93
94 @Override
95 public boolean clear(String hostname) {
96 requireNonNull(hostname, "hostname");
97 return cache.clear(hostname);
98 }
99 }