search: Handle index build errors gracefully (#108862)

* Close new index if we fail to build it.

* Respect context cancellation in getOrCreateIndex.
This commit is contained in:
Peter Štibraný
2025-07-29 17:40:16 +02:00
committed by GitHub
parent 1a246739ed
commit 41319f90bb
4 changed files with 137 additions and 16 deletions
@@ -332,3 +332,57 @@ func TestSearchGetOrCreateIndex(t *testing.T) {
require.Equal(t, int64(50), search.buildIndexCalls[0].size)
require.Equal(t, int64(11111111), search.buildIndexCalls[0].resourceVersion)
}
func TestSearchGetOrCreateIndexWithCancellation(t *testing.T) {
// Setup mock implementations
storage := &mockStorageBackend{
resourceStats: []ResourceStats{
{NamespacedResource: NamespacedResource{Namespace: "ns", Group: "group", Resource: "resource"}, Count: 50, ResourceVersion: 11111111},
},
}
search := &slowSearchBackend{
mockSearchBackend: mockSearchBackend{},
}
supplier := &TestDocumentBuilderSupplier{
GroupsResources: map[string]string{
"group": "resource",
},
}
// Create search support with the specified initMaxSize
opts := SearchOptions{
Backend: search,
Resources: supplier,
WorkerThreads: 1,
InitMinCount: 1, // set min count to default for this test
InitMaxCount: 0,
}
support, err := newSearchSupport(opts, storage, nil, nil, noop.NewTracerProvider().Tracer("test"), nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, support)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
_, err = support.getOrCreateIndex(ctx, NamespacedResource{Namespace: "ns", Group: "group", Resource: "resource"})
// Make sure we get context deadline error
require.ErrorIs(t, err, context.DeadlineExceeded)
// Wait until indexing is finished.
search.wg.Wait()
require.NotEmpty(t, search.buildIndexCalls)
}
type slowSearchBackend struct {
mockSearchBackend
wg sync.WaitGroup
}
func (m *slowSearchBackend) BuildIndex(ctx context.Context, key NamespacedResource, size int64, resourceVersion int64, fields SearchableDocumentFields, builder func(index ResourceIndex) (int64, error)) (ResourceIndex, error) {
m.wg.Add(1)
defer m.wg.Done()
time.Sleep(1 * time.Second)
return m.mockSearchBackend.BuildIndex(ctx, key, size, resourceVersion, fields, builder)
}