Skip to content

Commit

Permalink
Fix a bug with Limit list opt. (#1618)
Browse files Browse the repository at this point in the history
Previously, `Limit(n)` only looks at the first `n` objects. This could cause `List` to return less than `n` objects if other `opts` apply further filtering, even though there are more than `n` total number of objects matching the list options.
  • Loading branch information
ankel authored Aug 1, 2021
1 parent a4602c0 commit 9fe547c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
9 changes: 9 additions & 0 deletions pkg/cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,15 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca
Expect(informerCache.List(context.Background(), listObj, opts)).To(Succeed())
Expect(listObj.Items).Should(HaveLen(3))
})

It("should return a limited result set matching the correct label", func() {
listObj := &corev1.PodList{}
labelOpt := client.MatchingLabels(map[string]string{"common-label": "common"})
limitOpt := client.Limit(1)
By("verifying that only Limit (1) number of objects are retrieved from the cache")
Expect(informerCache.List(context.Background(), listObj, labelOpt, limitOpt)).To(Succeed())
Expect(listObj.Items).Should(HaveLen(1))
})
})

Context("with unstructured objects", func() {
Expand Down
4 changes: 2 additions & 2 deletions pkg/cache/internal/cache_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,10 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli
limitSet := listOpts.Limit > 0

runtimeObjs := make([]runtime.Object, 0, len(objs))
for i, item := range objs {
for _, item := range objs {
// if the Limit option is set and the number of items
// listed exceeds this limit, then stop reading.
if limitSet && int64(i) >= listOpts.Limit {
if limitSet && int64(len(runtimeObjs)) >= listOpts.Limit {
break
}
obj, isObj := item.(runtime.Object)
Expand Down

0 comments on commit 9fe547c

Please sign in to comment.