diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java index 86e4e03d99..e9de15ba52 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java @@ -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; @@ -307,7 +308,7 @@ public void addIndexers(Map>> indexers) { */ @Override public Stream list(String namespace, Predicate predicate) { - return mergeWithTempCacheForList(manager().list(namespace), namespace, predicate); + return mergeWithTempCacheForList(() -> manager().list(namespace), namespace, predicate); } /** @@ -318,7 +319,7 @@ public Stream list(String namespace, Predicate predicate) { */ @Override public Stream list(Predicate predicate) { - return mergeWithTempCacheForList(manager().list(), null, predicate); + return mergeWithTempCacheForList(() -> manager().list(), null, predicate); } /** @@ -347,19 +348,23 @@ public List 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 mergeWithTempCacheForList( - Stream stream, String namespace, Predicate predicate) { + Supplier> streamSupplier, String namespace, Predicate 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); var upToDateList = - stream + streamSupplier + .get() .map( r -> { var resourceID = ResourceID.fromResource(r); @@ -376,6 +381,7 @@ private Stream mergeWithTempCacheForList( return Stream.concat( tempResources.values().stream() + .filter(r -> !supersededIds.contains(ResourceID.fromResource(r))) .filter(filterResourceByNamespaceAndPredicate(namespace, predicate)), upToDateList.stream()); } @@ -394,6 +400,7 @@ private Stream mergeWithTempCacheForIndex( if (indexer == null) { throw new IllegalArgumentException("Indexer not found for: " + indexName); } + var supersededIds = idsSupersededByInformer(tempResources); var upToDateList = stream @@ -413,9 +420,12 @@ private Stream 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()); } @@ -452,10 +462,24 @@ public Stream 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 idsSupersededByInformer(Map tempResources) { + return tempResources.entrySet().stream() + .filter(e -> !isLaterThanLastSyncResourceVersion(e.getValue())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } @Override diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java index 01ee25e44c..4664c18c25 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java @@ -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; @@ -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); @@ -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(); @@ -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); @@ -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();