Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -307,7 +308,7 @@ public void addIndexers(Map<String, Function<R, List<String>>> indexers) {
*/
@Override
public Stream<R> list(String namespace, Predicate<R> predicate) {
return mergeWithTempCacheForList(manager().list(namespace), namespace, predicate);
return mergeWithTempCacheForList(() -> manager().list(namespace), namespace, predicate);
}

/**
Expand All @@ -318,7 +319,7 @@ public Stream<R> list(String namespace, Predicate<R> predicate) {
*/
@Override
public Stream<R> list(Predicate<R> predicate) {
return mergeWithTempCacheForList(manager().list(), null, predicate);
return mergeWithTempCacheForList(() -> manager().list(), null, predicate);
}

/**
Expand Down Expand Up @@ -347,19 +348,23 @@ public List<R> byIndex(String indexName, String indexKey) {
}

// namespace is filtered on informer manager level
// The informer stream is supplied lazily because the namespace-scoped list snapshots the informer
// cache as soon as it is created. The superseded ids have to be computed before that snapshot,
// otherwise a resource the informer catches up with in between is missing from both.
private Stream<R> mergeWithTempCacheForList(
Stream<R> stream, String namespace, Predicate<R> predicate) {
Supplier<Stream<R>> streamSupplier, String namespace, Predicate<R> predicate) {
if (!comparableResourceVersions || temporaryResourceCache.isEmpty()) {

return stream.filter(filterResourceByPredicate(predicate));
return streamSupplier.get().filter(filterResourceByPredicate(predicate));
}
var tempResources = new HashMap<>(temporaryResourceCache.getResources());
if (tempResources.isEmpty()) {
return stream.filter(filterResourceByPredicate(predicate));
return streamSupplier.get().filter(filterResourceByPredicate(predicate));
}
var supersededIds = idsSupersededByInformer(tempResources);
Comment thread
Copilot marked this conversation as resolved.
Resolved

var upToDateList =
stream
streamSupplier
.get()
.map(
r -> {
var resourceID = ResourceID.fromResource(r);
Expand All @@ -376,6 +381,7 @@ private Stream<R> mergeWithTempCacheForList(

return Stream.concat(
tempResources.values().stream()
.filter(r -> !supersededIds.contains(ResourceID.fromResource(r)))
.filter(filterResourceByNamespaceAndPredicate(namespace, predicate)),
upToDateList.stream());
}
Expand All @@ -394,6 +400,7 @@ private Stream<R> mergeWithTempCacheForIndex(
if (indexer == null) {
throw new IllegalArgumentException("Indexer not found for: " + indexName);
}
var supersededIds = idsSupersededByInformer(tempResources);

var upToDateList =
stream
Expand All @@ -413,9 +420,12 @@ private Stream<R> mergeWithTempCacheForIndex(
.filter(Objects::nonNull)
.toList();

// remaining temp resources are ghost resources — include only those matching the index
// remaining temp resources are ghost resources — include only those matching the index and
// not already superseded in the informer
return Stream.concat(
tempResources.values().stream().filter(r -> indexer.apply(r).contains(indexKey)),
tempResources.values().stream()
.filter(r -> !supersededIds.contains(ResourceID.fromResource(r)))
.filter(r -> indexer.apply(r).contains(indexKey)),
upToDateList.stream());
}

Expand Down Expand Up @@ -452,10 +462,24 @@ public Stream<ResourceID> keys() {
if (!comparableResourceVersions || temporaryResourceCache.isEmpty()) {
return manager().keys();
}
var tempResources = temporaryResourceCache.getResources();
var supersededIds = idsSupersededByInformer(tempResources);
var managerKeys = manager().keys().collect(Collectors.toSet());
var tempKeys = temporaryResourceCache.getResources().keySet();
return Stream.concat(
managerKeys.stream(), tempKeys.stream().filter(k -> !managerKeys.contains(k)));
managerKeys.stream(),
tempResources.keySet().stream()
.filter(k -> !managerKeys.contains(k) && !supersededIds.contains(k)));
}

/**
* Has to be evaluated before the informer state is read, so a resource that the informer catches
* up with in the meantime is not missing from both.
*/
private Set<ResourceID> idsSupersededByInformer(Map<ResourceID, R> tempResources) {
return tempResources.entrySet().stream()
.filter(e -> !isLaterThanLastSyncResourceVersion(e.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -374,6 +375,7 @@ void listAddsGhostResources() {
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource)));

var mim = mock(InformerManager.class);
stubLastSyncResourceVersion(mim, "1");
when(mim.list(nullable(String.class))).thenReturn(Stream.of(resource));
when(informerEventSource.manager()).thenReturn(mim);

Expand All @@ -382,6 +384,163 @@ void listAddsGhostResources() {
assertThat(result).containsExactlyInAnyOrder(resource, ghostResource);
}

@Test
void listSkipsGhostResourcesAlreadyCoveredByInformer() {
var resource = testDeployment();
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource)));

var mim = mock(InformerManager.class);
stubLastSyncResourceVersion(mim, DEFAULT_RESOURCE_VERSION);
when(mim.list(nullable(String.class))).thenReturn(Stream.of(resource));
when(informerEventSource.manager()).thenReturn(mim);

var result = informerEventSource.list(null, r -> true).toList();

assertThat(result).containsExactly(resource);
}

@Test
void byIndexSkipsOlderTempCacheResourceNoLongerInIndexedInformerResult() {
var staleTemp = testDeployment();
staleTemp.getMetadata().setLabels(Map.of("app", "key"));

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(staleTemp), staleTemp)));

var informerManager = mock(InformerManager.class);
stubLastSyncResourceVersion(informerManager, "5");
when(informerManager.byIndexStream(any(), any())).thenReturn(Stream.empty());
when(informerEventSource.manager()).thenReturn(informerManager);
informerEventSource.addIndexers(
Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app"))));

var result = informerEventSource.byIndexStream("idx", "key").toList();

assertThat(result).isEmpty();
}

@Test
void byIndexIncludesGhostResourceNotYetSeenByInformer() {
var ghost = testDeployment();
ghost.getMetadata().setLabels(Map.of("app", "key"));

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghost), ghost)));

var informerManager = mock(InformerManager.class);
stubLastSyncResourceVersion(informerManager, "1");
when(informerManager.byIndexStream(any(), any())).thenReturn(Stream.empty());
when(informerEventSource.manager()).thenReturn(informerManager);
informerEventSource.addIndexers(
Map.of("idx", d -> List.of(d.getMetadata().getLabels().get("app"))));

var result = informerEventSource.byIndexStream("idx", "key").toList();

assertThat(result).containsExactly(ghost);
}

@Test
void listKeepsGhostResourceIfInformerCatchesUpWhileReadingTheInformerState() {
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");
var other = testDeployment();
other.getMetadata().setName("other");
var lastSync = new AtomicReference<>("1");

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource)));
var mim = mock(InformerManager.class);
when(mim.isWatchingNamespace(any())).thenReturn(true);
when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get());
when(mim.list(nullable(String.class)))
.thenReturn(Stream.of(other).peek(r -> lastSync.set("5")));
when(informerEventSource.manager()).thenReturn(mim);

var result = informerEventSource.list(null, r -> true).toList();

assertThat(result).containsExactlyInAnyOrder(other, ghostResource);
}

@Test
void listKeepsGhostResourceIfInformerCatchesUpWhenTheInformerSnapshotIsTaken() {
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");
var other = testDeployment();
other.getMetadata().setName("other");
var lastSync = new AtomicReference<>("1");

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource)));
var mim = mock(InformerManager.class);
when(mim.isWatchingNamespace(any())).thenReturn(true);
when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get());
when(mim.list(nullable(String.class)))
.thenAnswer(
i -> {
lastSync.set("5");
return Stream.of(other);
});
when(informerEventSource.manager()).thenReturn(mim);

var result = informerEventSource.list(null, r -> true).toList();

assertThat(result).containsExactlyInAnyOrder(other, ghostResource);
}

@Test
void byIndexKeepsGhostResourceIfInformerCatchesUpWhileReadingTheInformerState() {
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");
var other = testDeployment();
other.getMetadata().setName("other");
var lastSync = new AtomicReference<>("1");

when(temporaryResourceCache.getResources())
.thenReturn(new HashMap<>(Map.of(ResourceID.fromResource(ghostResource), ghostResource)));
var mim = mock(InformerManager.class);
when(mim.isWatchingNamespace(any())).thenReturn(true);
when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get());
when(mim.byIndexStream(any(), any())).thenReturn(Stream.of(other).peek(r -> lastSync.set("5")));
when(informerEventSource.manager()).thenReturn(mim);
informerEventSource.addIndexers(Map.of("idx", d -> List.of("key")));

var result = informerEventSource.byIndexStream("idx", "key").toList();

assertThat(result).containsExactlyInAnyOrder(other, ghostResource);
}

@Test
void keysKeepGhostResourceKeyIfInformerCatchesUpWhileReadingTheInformerState() {
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");
var other = testDeployment();
other.getMetadata().setName("other");
var ghostResourceId = ResourceID.fromResource(ghostResource);
var otherId = ResourceID.fromResource(other);
var lastSync = new AtomicReference<>("1");

when(temporaryResourceCache.getResources()).thenReturn(Map.of(ghostResourceId, ghostResource));
when(temporaryResourceCache.isEmpty()).thenReturn(false);
var mim = mock(InformerManager.class);
when(mim.isWatchingNamespace(any())).thenReturn(true);
when(mim.lastSyncResourceVersion(any())).thenAnswer(i -> lastSync.get());
when(mim.keys()).thenReturn(Stream.of(otherId).peek(r -> lastSync.set("5")));
when(informerEventSource.manager()).thenReturn(mim);

var result = informerEventSource.keys().toList();

assertThat(result).containsExactlyInAnyOrder(otherId, ghostResourceId);
}

private void stubLastSyncResourceVersion(InformerManager mim, String resourceVersion) {
when(mim.isWatchingNamespace(any())).thenReturn(true);
when(mim.lastSyncResourceVersion(any())).thenReturn(resourceVersion);
}

@Test
void byIndexStreamReplacesFromTempCache() {
var original = testDeployment();
Expand Down Expand Up @@ -436,6 +595,7 @@ void keysIncludeGhostResourceKeys() {
when(temporaryResourceCache.isEmpty()).thenReturn(false);

var mim = mock(InformerManager.class);
stubLastSyncResourceVersion(mim, "1");
when(mim.keys()).thenReturn(Stream.of(resourceId));
when(mim.contains(ghostResourceId)).thenReturn(false);
when(informerEventSource.manager()).thenReturn(mim);
Expand All @@ -445,6 +605,28 @@ void keysIncludeGhostResourceKeys() {
assertThat(result).containsExactlyInAnyOrder(resourceId, ghostResourceId);
}

@Test
void keysSkipGhostResourceKeysAlreadyCoveredByInformer() {
var resource = testDeployment();
var ghostResource = testDeployment();
ghostResource.getMetadata().setName("ghost");

var resourceId = ResourceID.fromResource(resource);
var ghostResourceId = ResourceID.fromResource(ghostResource);

when(temporaryResourceCache.getResources()).thenReturn(Map.of(ghostResourceId, ghostResource));
when(temporaryResourceCache.isEmpty()).thenReturn(false);

var mim = mock(InformerManager.class);
stubLastSyncResourceVersion(mim, DEFAULT_RESOURCE_VERSION);
when(mim.keys()).thenReturn(Stream.of(resourceId));
when(informerEventSource.manager()).thenReturn(mim);

var result = informerEventSource.keys().toList();

assertThat(result).containsExactly(resourceId);
}

@Test
void keysDoNotDuplicateExistingKeys() {
var resource = testDeployment();
Expand Down