Skip to content

Commit 1db0973

Browse files
committed
feat: resource cache
Signed-off-by: Attila Mészáros <[email protected]>
1 parent 6c738fd commit 1db0973

File tree

1 file changed

+55
-0
lines changed
  • operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/support

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package io.javaoperatorsdk.operator.processing.support;
2+
3+
import java.util.concurrent.ConcurrentHashMap;
4+
import java.util.function.BiPredicate;
5+
6+
import io.fabric8.kubernetes.api.model.HasMetadata;
7+
import io.javaoperatorsdk.operator.processing.event.ResourceID;
8+
9+
public class ResourceCache<P extends HasMetadata> {
10+
11+
private BiPredicate<Pair<P>, P> evictionPredicate;
12+
private ConcurrentHashMap<ResourceID, Pair<P>> cache = new ConcurrentHashMap<>();
13+
14+
public ResourceCache(BiPredicate<Pair<P>, P> evictionPredicate) {
15+
this.evictionPredicate = evictionPredicate;
16+
}
17+
18+
public void cacheResource(P beforeUpdate, P afterUpdate) {
19+
var resourceId = ResourceID.fromResource(beforeUpdate);
20+
cache.put(resourceId, new Pair<>(beforeUpdate, afterUpdate));
21+
}
22+
23+
public P getFreshResource(P newVersion) {
24+
var resourceId = ResourceID.fromResource(newVersion);
25+
var pair = cache.get(resourceId);
26+
if (pair == null) {
27+
return newVersion;
28+
}
29+
if (evictionPredicate.test(pair, newVersion)) {
30+
cache.remove(resourceId);
31+
return newVersion;
32+
} else {
33+
return pair.afterUpdate();
34+
}
35+
}
36+
37+
public record Pair<T extends HasMetadata>(T beforeUpdate, T afterUpdate) {}
38+
39+
public static class ResourceVersionComparePredicate<T extends HasMetadata>
40+
implements BiPredicate<Pair<T>, T> {
41+
@Override
42+
public boolean test(Pair<T> updatePair, T newVersion) {
43+
return Long.parseLong(updatePair.afterUpdate().getMetadata().getResourceVersion())
44+
<= Long.parseLong(newVersion.getMetadata().getResourceVersion());
45+
}
46+
}
47+
48+
public static class ResourceVersionEqualityPredicate<T extends HasMetadata>
49+
implements BiPredicate<Pair<T>, T> {
50+
@Override
51+
public boolean test(Pair<T> updatePair, T newVersion) {
52+
return !updatePair.beforeUpdate().equals(newVersion.getMetadata().getResourceVersion());
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)