From 3350323f911b5b9db454e9a26ac144c3391d254c Mon Sep 17 00:00:00 2001 From: Silvio Moioli Date: Wed, 12 Feb 2025 09:46:10 +0100 Subject: [PATCH] sql: propagate and use contexts (#465) Previous SQLite-related code used context.Background() and context.TODO() because it was not developed with context awareness. This commit propagates the main Steve context so that it can be used when interacting with SQL context-aware functions. This PR removes all production-code use of context.Background() and context.TODO() and replaces test-code use of TODO with Background. Contributes to rancher/rancher#47825 --- pkg/server/server.go | 2 +- pkg/sqlcache/db/client_test.go | 4 +- .../informer/factory/informer_factory.go | 7 ++- .../informer/factory/informer_factory_test.go | 31 +++++----- pkg/sqlcache/informer/indexer.go | 15 +++-- pkg/sqlcache/informer/indexer_test.go | 57 ++++++++++++------- pkg/sqlcache/informer/informer.go | 10 ++-- pkg/sqlcache/informer/informer_test.go | 20 +++---- pkg/sqlcache/informer/listoption_indexer.go | 6 +- .../informer/listoption_indexer_test.go | 14 ++--- pkg/sqlcache/integration_test.go | 2 +- pkg/sqlcache/store/store.go | 20 ++++--- pkg/sqlcache/store/store_test.go | 34 +++++------ pkg/stores/sqlproxy/proxy_mocks_test.go | 8 +-- pkg/stores/sqlproxy/proxy_store.go | 12 ++-- pkg/stores/sqlproxy/proxy_store_test.go | 39 ++++++++----- 16 files changed, 160 insertions(+), 121 deletions(-) diff --git a/pkg/server/server.go b/pkg/server/server.go index a9711e77..a2ffb1d5 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -187,7 +187,7 @@ func setup(ctx context.Context, server *Server) error { var onSchemasHandler schemacontroller.SchemasHandlerFunc if server.SQLCache { - s, err := sqlproxy.NewProxyStore(cols, cf, summaryCache, summaryCache, nil) + s, err := sqlproxy.NewProxyStore(ctx, cols, cf, summaryCache, summaryCache, nil) if err != nil { panic(err) } diff --git a/pkg/sqlcache/db/client_test.go b/pkg/sqlcache/db/client_test.go index 0f7f5290..4eef36e6 100644 --- a/pkg/sqlcache/db/client_test.go +++ b/pkg/sqlcache/db/client_test.go @@ -67,7 +67,7 @@ func TestQueryForRows(t *testing.T) { c := SetupMockConnection(t) client := SetupClient(t, c, nil, nil) s := NewMockStmt(gomock.NewController(t)) - ctx := context.TODO() + ctx := context.Background() r := &sql.Rows{} s.EXPECT().QueryContext(ctx).Return(r, nil) rows, err := client.QueryForRows(ctx, s) @@ -79,7 +79,7 @@ func TestQueryForRows(t *testing.T) { c := SetupMockConnection(t) client := SetupClient(t, c, nil, nil) s := NewMockStmt(gomock.NewController(t)) - ctx := context.TODO() + ctx := context.Background() s.EXPECT().QueryContext(ctx).Return(nil, fmt.Errorf("error")) _, err := client.QueryForRows(ctx, s) assert.NotNil(t, err) diff --git a/pkg/sqlcache/informer/factory/informer_factory.go b/pkg/sqlcache/informer/factory/informer_factory.go index 71470200..d2a431d9 100644 --- a/pkg/sqlcache/informer/factory/informer_factory.go +++ b/pkg/sqlcache/informer/factory/informer_factory.go @@ -4,6 +4,7 @@ Package factory provides a cache factory for the sql-based cache. package factory import ( + "context" "fmt" "os" "sync" @@ -43,7 +44,7 @@ type guardedInformer struct { mutex *sync.Mutex } -type newInformer func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespace bool) (*informer.Informer, error) +type newInformer func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespace bool) (*informer.Informer, error) type Cache struct { informer.ByOptionsLister @@ -84,7 +85,7 @@ func NewCacheFactory() (*CacheFactory, error) { // CacheFor returns an informer for given GVK, using sql store indexed with fields, using the specified client. For virtual fields, they must be added by the transform function // and specified by fields to be used for later fields. -func (f *CacheFactory) CacheFor(fields [][]string, transform cache.TransformFunc, client dynamic.ResourceInterface, gvk schema.GroupVersionKind, namespaced bool, watchable bool) (Cache, error) { +func (f *CacheFactory) CacheFor(ctx context.Context, fields [][]string, transform cache.TransformFunc, client dynamic.ResourceInterface, gvk schema.GroupVersionKind, namespaced bool, watchable bool) (Cache, error) { // First of all block Reset() until we are done f.mutex.RLock() defer f.mutex.RUnlock() @@ -120,7 +121,7 @@ func (f *CacheFactory) CacheFor(fields [][]string, transform cache.TransformFunc _, encryptResourceAlways := defaultEncryptedResourceTypes[gvk] shouldEncrypt := f.encryptAll || encryptResourceAlways - i, err := f.newInformer(client, fields, transform, gvk, f.dbClient, shouldEncrypt, namespaced) + i, err := f.newInformer(ctx, client, fields, transform, gvk, f.dbClient, shouldEncrypt, namespaced) if err != nil { return Cache{}, err } diff --git a/pkg/sqlcache/informer/factory/informer_factory_test.go b/pkg/sqlcache/informer/factory/informer_factory_test.go index 3abacae2..658f5a60 100644 --- a/pkg/sqlcache/informer/factory/informer_factory_test.go +++ b/pkg/sqlcache/informer/factory/informer_factory_test.go @@ -1,6 +1,7 @@ package factory import ( + "context" "os" "testing" "time" @@ -73,7 +74,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -95,12 +96,12 @@ func TestCacheFor(t *testing.T) { }() var c Cache var err error - c, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) // this sleep is critical to the test. It ensure there has been enough time for expected function like Run to be invoked in their go routines. time.Sleep(1 * time.Second) - c2, err := f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c2, err := f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, c, c2) }}) @@ -118,7 +119,7 @@ func TestCacheFor(t *testing.T) { // need to set this so Run function is not nil SharedIndexInformer: sii, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -138,7 +139,7 @@ func TestCacheFor(t *testing.T) { close(f.stopCh) }() var err error - _, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + _, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.NotNil(t, err) time.Sleep(2 * time.Second) }}) @@ -160,7 +161,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -178,7 +179,7 @@ func TestCacheFor(t *testing.T) { close(f.stopCh) var c Cache var err error - c, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) time.Sleep(1 * time.Second) @@ -199,7 +200,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -221,7 +222,7 @@ func TestCacheFor(t *testing.T) { }() var c Cache var err error - c, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) time.Sleep(1 * time.Second) @@ -247,7 +248,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -269,7 +270,7 @@ func TestCacheFor(t *testing.T) { }() var c Cache var err error - c, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) time.Sleep(1 * time.Second) @@ -294,7 +295,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt, namespaced bool) (*informer.Informer, error) { assert.Equal(t, client, dynamicClient) assert.Equal(t, fields, fields) assert.Equal(t, expectedGVK, gvk) @@ -316,7 +317,7 @@ func TestCacheFor(t *testing.T) { }() var c Cache var err error - c, err = f.CacheFor(fields, nil, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, nil, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) time.Sleep(1 * time.Second) @@ -341,7 +342,7 @@ func TestCacheFor(t *testing.T) { expectedC := Cache{ ByOptionsLister: i, } - testNewInformer := func(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*informer.Informer, error) { + testNewInformer := func(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*informer.Informer, error) { // we can't test func == func, so instead we check if the output was as expected input := "someinput" ouput, err := transform(input) @@ -371,7 +372,7 @@ func TestCacheFor(t *testing.T) { }() var c Cache var err error - c, err = f.CacheFor(fields, transformFunc, dynamicClient, expectedGVK, false, true) + c, err = f.CacheFor(context.Background(), fields, transformFunc, dynamicClient, expectedGVK, false, true) assert.Nil(t, err) assert.Equal(t, expectedC, c) time.Sleep(1 * time.Second) diff --git a/pkg/sqlcache/informer/indexer.go b/pkg/sqlcache/informer/indexer.go index b5b590fa..78b81882 100644 --- a/pkg/sqlcache/informer/indexer.go +++ b/pkg/sqlcache/informer/indexer.go @@ -43,6 +43,8 @@ const ( // Indexer is a SQLite-backed cache.Indexer which builds upon Store adding an index table type Indexer struct { + ctx context.Context + Store indexers cache.Indexers indexersLock sync.RWMutex @@ -75,10 +77,10 @@ type Store interface { } // NewIndexer returns a cache.Indexer backed by SQLite for objects of the given example type -func NewIndexer(indexers cache.Indexers, s Store) (*Indexer, error) { +func NewIndexer(ctx context.Context, indexers cache.Indexers, s Store) (*Indexer, error) { dbName := db.Sanitize(s.GetName()) - err := s.WithTransaction(context.Background(), true, func(tx transaction.Client) error { + err := s.WithTransaction(ctx, true, func(tx transaction.Client) error { createTableQuery := fmt.Sprintf(createTableFmt, dbName) _, err := tx.Exec(createTableQuery) if err != nil { @@ -96,6 +98,7 @@ func NewIndexer(indexers cache.Indexers, s Store) (*Indexer, error) { } i := &Indexer{ + ctx: ctx, Store: s, indexers: indexers, } @@ -187,7 +190,7 @@ func (i *Indexer) Index(indexName string, obj any) (result []any, err error) { params = append(params, value) } - rows, err := i.QueryForRows(context.TODO(), stmt, params...) + rows, err := i.QueryForRows(i.ctx, stmt, params...) if err != nil { return nil, &db.QueryError{QueryString: query, Err: err} } @@ -197,7 +200,7 @@ func (i *Indexer) Index(indexName string, obj any) (result []any, err error) { // ByIndex returns the stored objects whose set of indexed values // for the named index includes the given indexed value func (i *Indexer) ByIndex(indexName, indexedValue string) ([]any, error) { - rows, err := i.QueryForRows(context.TODO(), i.listByIndexStmt, indexName, indexedValue) + rows, err := i.QueryForRows(i.ctx, i.listByIndexStmt, indexName, indexedValue) if err != nil { return nil, &db.QueryError{QueryString: i.listByIndexQuery, Err: err} } @@ -213,7 +216,7 @@ func (i *Indexer) IndexKeys(indexName, indexedValue string) ([]string, error) { return nil, fmt.Errorf("Index with name %s does not exist", indexName) } - rows, err := i.QueryForRows(context.TODO(), i.listKeysByIndexStmt, indexName, indexedValue) + rows, err := i.QueryForRows(i.ctx, i.listKeysByIndexStmt, indexName, indexedValue) if err != nil { return nil, &db.QueryError{QueryString: i.listKeysByIndexQuery, Err: err} } @@ -231,7 +234,7 @@ func (i *Indexer) ListIndexFuncValues(name string) []string { // safeListIndexFuncValues returns all the indexed values of the given index func (i *Indexer) safeListIndexFuncValues(indexName string) ([]string, error) { - rows, err := i.QueryForRows(context.TODO(), i.listIndexValuesStmt, indexName) + rows, err := i.QueryForRows(i.ctx, i.listIndexValuesStmt, indexName) if err != nil { return nil, &db.QueryError{QueryString: i.listIndexValuesQuery, Err: err} } diff --git a/pkg/sqlcache/informer/indexer_test.go b/pkg/sqlcache/informer/indexer_test.go index 4c10b5de..584722d3 100644 --- a/pkg/sqlcache/informer/indexer_test.go +++ b/pkg/sqlcache/informer/indexer_test.go @@ -64,7 +64,7 @@ func TestNewIndexer(t *testing.T) { store.EXPECT().Prepare(fmt.Sprintf(listByIndexFmt, storeName, storeName)) store.EXPECT().Prepare(fmt.Sprintf(listKeyByIndexFmt, storeName)) store.EXPECT().Prepare(fmt.Sprintf(listIndexValuesFmt, storeName)) - indexer, err := NewIndexer(indexers, store) + indexer, err := NewIndexer(context.Background(), indexers, store) assert.Nil(t, err) assert.Equal(t, cache.Indexers(indexers), indexer.indexers) }}) @@ -79,7 +79,7 @@ func TestNewIndexer(t *testing.T) { } store.EXPECT().GetName().AnyTimes().Return("someStoreName") store.EXPECT().WithTransaction(gomock.Any(), true, gomock.Any()).Return(fmt.Errorf("error")) - _, err := NewIndexer(indexers, store) + _, err := NewIndexer(context.Background(), indexers, store) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewIndexer() with Client Exec() error on first call to Exec(), should return error", test: func(t *testing.T) { @@ -103,7 +103,7 @@ func TestNewIndexer(t *testing.T) { t.Fail() } }) - _, err := NewIndexer(indexers, store) + _, err := NewIndexer(context.Background(), indexers, store) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewIndexer() with Client Exec() error on second call to Exec(), should return error", test: func(t *testing.T) { @@ -129,7 +129,7 @@ func TestNewIndexer(t *testing.T) { } }) - _, err := NewIndexer(indexers, store) + _, err := NewIndexer(context.Background(), indexers, store) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewIndexer() with Client Commit() error, should return error", test: func(t *testing.T) { @@ -153,7 +153,7 @@ func TestNewIndexer(t *testing.T) { t.Fail() } }) - _, err := NewIndexer(indexers, store) + _, err := NewIndexer(context.Background(), indexers, store) assert.NotNil(t, err) }}) t.Parallel() @@ -177,6 +177,7 @@ func TestAfterUpsert(t *testing.T) { deleteIndicesStmt := NewMockStmt(gomock.NewController(t)) addIndexStmt := NewMockStmt(gomock.NewController(t)) indexer := &Indexer{ + ctx: context.Background(), Store: store, indexers: map[string]cache.IndexFunc{ "a": func(obj interface{}) ([]string, error) { @@ -199,6 +200,7 @@ func TestAfterUpsert(t *testing.T) { objKey := "key" deleteIndicesStmt := NewMockStmt(gomock.NewController(t)) indexer := &Indexer{ + ctx: context.Background(), Store: store, indexers: map[string]cache.IndexFunc{ @@ -221,6 +223,7 @@ func TestAfterUpsert(t *testing.T) { addIndexStmt := NewMockStmt(gomock.NewController(t)) objKey := "key" indexer := &Indexer{ + ctx: context.Background(), Store: store, indexers: map[string]cache.IndexFunc{ "a": func(obj interface{}) ([]string, error) { @@ -258,6 +261,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -268,7 +272,7 @@ func TestIndex(t *testing.T) { } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject}, nil) @@ -283,6 +287,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -293,7 +298,7 @@ func TestIndex(t *testing.T) { } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject, testObject}, nil) @@ -308,6 +313,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -318,7 +324,7 @@ func TestIndex(t *testing.T) { } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{}, nil) @@ -332,6 +338,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -351,6 +358,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -361,7 +369,7 @@ func TestIndex(t *testing.T) { } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(nil, fmt.Errorf("error")) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(nil, fmt.Errorf("error")) _, err := indexer.Index(indexName, testObject) assert.NotNil(t, err) }}) @@ -372,6 +380,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -382,7 +391,7 @@ func TestIndex(t *testing.T) { } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject}, fmt.Errorf("error")) @@ -396,6 +405,7 @@ func TestIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, indexers: map[string]cache.IndexFunc{ @@ -409,7 +419,7 @@ func TestIndex(t *testing.T) { store.EXPECT().GetName().Return("name") stmt := &sql.Stmt{} store.EXPECT().Prepare(fmt.Sprintf(selectQueryFmt, "name", ", ?")).Return(stmt) - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey, objKey+"2").Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey, objKey+"2").Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject}, nil) @@ -439,12 +449,13 @@ func TestByIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject}, nil) @@ -459,12 +470,13 @@ func TestByIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject, testObject}, nil) @@ -479,12 +491,13 @@ func TestByIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{}, nil) @@ -498,11 +511,12 @@ func TestByIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(nil, fmt.Errorf("error")) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(nil, fmt.Errorf("error")) _, err := indexer.ByIndex(indexName, objKey) assert.NotNil(t, err) }}) @@ -513,12 +527,13 @@ func TestByIndex(t *testing.T) { objKey := "key" indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } testObject := testStoreObject{Id: "something", Val: "a"} - store.EXPECT().QueryForRows(context.TODO(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listByIndexStmt, indexName, objKey).Return(rows, nil) store.EXPECT().GetType().Return(reflect.TypeOf(testObject)) store.EXPECT().GetShouldEncrypt().Return(false) store.EXPECT().ReadObjects(rows, reflect.TypeOf(testObject), false).Return([]any{testObject}, fmt.Errorf("error")) @@ -545,10 +560,11 @@ func TestListIndexFuncValues(t *testing.T) { listStmt := &sql.Stmt{} indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } - store.EXPECT().QueryForRows(context.TODO(), indexer.listIndexValuesStmt, indexName).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listIndexValuesStmt, indexName).Return(rows, nil) store.EXPECT().ReadStrings(rows).Return([]string{"somestrings"}, nil) vals := indexer.ListIndexFuncValues(indexName) assert.Equal(t, []string{"somestrings"}, vals) @@ -558,10 +574,11 @@ func TestListIndexFuncValues(t *testing.T) { listStmt := &sql.Stmt{} indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } - store.EXPECT().QueryForRows(context.TODO(), indexer.listIndexValuesStmt, indexName).Return(nil, fmt.Errorf("error")) + store.EXPECT().QueryForRows(context.Background(), indexer.listIndexValuesStmt, indexName).Return(nil, fmt.Errorf("error")) assert.Panics(t, func() { indexer.ListIndexFuncValues(indexName) }) }}) tests = append(tests, testCase{description: "ListIndexFuncvalues() with ReadStrings() error returned from store, should panic", test: func(t *testing.T) { @@ -570,10 +587,11 @@ func TestListIndexFuncValues(t *testing.T) { listStmt := &sql.Stmt{} indexName := "someindexname" indexer := &Indexer{ + ctx: context.Background(), Store: store, listByIndexStmt: listStmt, } - store.EXPECT().QueryForRows(context.TODO(), indexer.listIndexValuesStmt, indexName).Return(rows, nil) + store.EXPECT().QueryForRows(context.Background(), indexer.listIndexValuesStmt, indexName).Return(rows, nil) store.EXPECT().ReadStrings(rows).Return([]string{"somestrings"}, fmt.Errorf("error")) assert.Panics(t, func() { indexer.ListIndexFuncValues(indexName) }) }}) @@ -599,6 +617,7 @@ func TestGetIndexers(t *testing.T) { }, } indexer := &Indexer{ + ctx: context.Background(), indexers: expectedIndexers, } indexers := indexer.GetIndexers() diff --git a/pkg/sqlcache/informer/informer.go b/pkg/sqlcache/informer/informer.go index a54d9980..5d614fc4 100644 --- a/pkg/sqlcache/informer/informer.go +++ b/pkg/sqlcache/informer/informer.go @@ -35,14 +35,14 @@ var newInformer = cache.NewSharedIndexInformer // NewInformer returns a new SQLite-backed Informer for the type specified by schema in unstructured.Unstructured form // using the specified client -func NewInformer(client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*Informer, error) { +func NewInformer(ctx context.Context, client dynamic.ResourceInterface, fields [][]string, transform cache.TransformFunc, gvk schema.GroupVersionKind, db db.Client, shouldEncrypt bool, namespaced bool) (*Informer, error) { listWatcher := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - a, err := client.List(context.Background(), options) + a, err := client.List(ctx, options) return a, err }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - return client.Watch(context.Background(), options) + return client.Watch(ctx, options) }, } @@ -69,11 +69,11 @@ func NewInformer(client dynamic.ResourceInterface, fields [][]string, transform name := informerNameFromGVK(gvk) - s, err := sqlStore.NewStore(example, cache.DeletionHandlingMetaNamespaceKeyFunc, db, shouldEncrypt, name) + s, err := sqlStore.NewStore(ctx, example, cache.DeletionHandlingMetaNamespaceKeyFunc, db, shouldEncrypt, name) if err != nil { return nil, err } - loi, err := NewListOptionIndexer(fields, s, namespaced) + loi, err := NewListOptionIndexer(ctx, fields, s, namespaced) if err != nil { return nil, err } diff --git a/pkg/sqlcache/informer/informer_test.go b/pkg/sqlcache/informer/informer_test.go index 60509f4d..408bb8b4 100644 --- a/pkg/sqlcache/informer/informer_test.go +++ b/pkg/sqlcache/informer/informer_test.go @@ -79,7 +79,7 @@ func TestNewInformer(t *testing.T) { } }) - informer, err := NewInformer(dynamicClient, fields, nil, gvk, dbClient, false, true) + informer, err := NewInformer(context.Background(), dynamicClient, fields, nil, gvk, dbClient, false, true) assert.Nil(t, err) assert.NotNil(t, informer.ByOptionsLister) assert.NotNil(t, informer.SharedIndexInformer) @@ -103,7 +103,7 @@ func TestNewInformer(t *testing.T) { } }) - _, err := NewInformer(dynamicClient, fields, nil, gvk, dbClient, false, true) + _, err := NewInformer(context.Background(), dynamicClient, fields, nil, gvk, dbClient, false, true) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewInformer() with errors returned from NewIndexer(), should return an error", test: func(t *testing.T) { @@ -138,7 +138,7 @@ func TestNewInformer(t *testing.T) { } }) - _, err := NewInformer(dynamicClient, fields, nil, gvk, dbClient, false, true) + _, err := NewInformer(context.Background(), dynamicClient, fields, nil, gvk, dbClient, false, true) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewInformer() with errors returned from NewListOptionIndexer(), should return an error", test: func(t *testing.T) { @@ -190,7 +190,7 @@ func TestNewInformer(t *testing.T) { } }) - _, err := NewInformer(dynamicClient, fields, nil, gvk, dbClient, false, true) + _, err := NewInformer(context.Background(), dynamicClient, fields, nil, gvk, dbClient, false, true) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewInformer() with transform func", test: func(t *testing.T) { @@ -253,7 +253,7 @@ func TestNewInformer(t *testing.T) { transformFunc := func(input interface{}) (interface{}, error) { return "someoutput", nil } - informer, err := NewInformer(dynamicClient, fields, transformFunc, gvk, dbClient, false, true) + informer, err := NewInformer(context.Background(), dynamicClient, fields, transformFunc, gvk, dbClient, false, true) assert.Nil(t, err) assert.NotNil(t, informer.ByOptionsLister) assert.NotNil(t, informer.SharedIndexInformer) @@ -289,7 +289,7 @@ func TestNewInformer(t *testing.T) { transformFunc := func(input interface{}) (interface{}, error) { return "someoutput", nil } - _, err := NewInformer(dynamicClient, fields, transformFunc, gvk, dbClient, false, true) + _, err := NewInformer(context.Background(), dynamicClient, fields, transformFunc, gvk, dbClient, false, true) assert.Error(t, err) newInformer = cache.NewSharedIndexInformer }}) @@ -324,8 +324,8 @@ func TestInformerListByOptions(t *testing.T) { } expectedTotal := len(expectedList.Items) expectedContinueToken := "123" - indexer.EXPECT().ListByOptions(context.TODO(), lo, partitions, ns).Return(expectedList, expectedTotal, expectedContinueToken, nil) - list, total, continueToken, err := informer.ListByOptions(context.TODO(), lo, partitions, ns) + indexer.EXPECT().ListByOptions(context.Background(), lo, partitions, ns).Return(expectedList, expectedTotal, expectedContinueToken, nil) + list, total, continueToken, err := informer.ListByOptions(context.Background(), lo, partitions, ns) assert.Nil(t, err) assert.Equal(t, expectedList, list) assert.Equal(t, len(expectedList.Items), total) @@ -339,8 +339,8 @@ func TestInformerListByOptions(t *testing.T) { lo := ListOptions{} var partitions []partition.Partition ns := "somens" - indexer.EXPECT().ListByOptions(context.TODO(), lo, partitions, ns).Return(nil, 0, "", fmt.Errorf("error")) - _, _, _, err := informer.ListByOptions(context.TODO(), lo, partitions, ns) + indexer.EXPECT().ListByOptions(context.Background(), lo, partitions, ns).Return(nil, 0, "", fmt.Errorf("error")) + _, _, _, err := informer.ListByOptions(context.Background(), lo, partitions, ns) assert.NotNil(t, err) }}) t.Parallel() diff --git a/pkg/sqlcache/informer/listoption_indexer.go b/pkg/sqlcache/informer/listoption_indexer.go index 080657a9..0e1158ef 100644 --- a/pkg/sqlcache/informer/listoption_indexer.go +++ b/pkg/sqlcache/informer/listoption_indexer.go @@ -73,12 +73,12 @@ const ( // NewListOptionIndexer returns a SQLite-backed cache.Indexer of unstructured.Unstructured Kubernetes resources of a certain GVK // ListOptionIndexer is also able to satisfy ListOption queries on indexed (sub)fields. // Fields are specified as slices (e.g. "metadata.resourceVersion" is ["metadata", "resourceVersion"]) -func NewListOptionIndexer(fields [][]string, s Store, namespaced bool) (*ListOptionIndexer, error) { +func NewListOptionIndexer(ctx context.Context, fields [][]string, s Store, namespaced bool) (*ListOptionIndexer, error) { // necessary in order to gob/ungob unstructured.Unstructured objects gob.Register(map[string]interface{}{}) gob.Register([]interface{}{}) - i, err := NewIndexer(cache.Indexers{}, s) + i, err := NewIndexer(ctx, cache.Indexers{}, s) if err != nil { return nil, err } @@ -114,7 +114,7 @@ func NewListOptionIndexer(fields [][]string, s Store, namespaced bool) (*ListOpt qmarks := make([]string, len(indexedFields)) setStatements := make([]string, len(indexedFields)) - err = l.WithTransaction(context.Background(), true, func(tx transaction.Client) error { + err = l.WithTransaction(ctx, true, func(tx transaction.Client) error { _, err = tx.Exec(fmt.Sprintf(createFieldsTableFmt, dbName, strings.Join(columnDefs, ", "))) if err != nil { return err diff --git a/pkg/sqlcache/informer/listoption_indexer_test.go b/pkg/sqlcache/informer/listoption_indexer_test.go index fa36db55..16198144 100644 --- a/pkg/sqlcache/informer/listoption_indexer_test.go +++ b/pkg/sqlcache/informer/listoption_indexer_test.go @@ -72,7 +72,7 @@ func TestNewListOptionIndexer(t *testing.T) { } }) - loi, err := NewListOptionIndexer(fields, store, true) + loi, err := NewListOptionIndexer(context.Background(), fields, store, true) assert.Nil(t, err) assert.NotNil(t, loi) }}) @@ -93,7 +93,7 @@ func TestNewListOptionIndexer(t *testing.T) { } }) - _, err := NewListOptionIndexer(fields, store, false) + _, err := NewListOptionIndexer(context.Background(), fields, store, false) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewListOptionIndexer() with error returned from Begin(), should return an error", test: func(t *testing.T) { @@ -122,7 +122,7 @@ func TestNewListOptionIndexer(t *testing.T) { store.EXPECT().WithTransaction(gomock.Any(), true, gomock.Any()).Return(fmt.Errorf("error")) - _, err := NewListOptionIndexer(fields, store, false) + _, err := NewListOptionIndexer(context.Background(), fields, store, false) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewListOptionIndexer() with error from Exec() when creating fields table, should return an error", test: func(t *testing.T) { @@ -159,7 +159,7 @@ func TestNewListOptionIndexer(t *testing.T) { } }) - _, err := NewListOptionIndexer(fields, store, true) + _, err := NewListOptionIndexer(context.Background(), fields, store, true) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewListOptionIndexer() with error from create-labels, should return an error", test: func(t *testing.T) { @@ -200,7 +200,7 @@ func TestNewListOptionIndexer(t *testing.T) { } }) - _, err := NewListOptionIndexer(fields, store, true) + _, err := NewListOptionIndexer(context.Background(), fields, store, true) assert.NotNil(t, err) }}) tests = append(tests, testCase{description: "NewListOptionIndexer() with error from Commit(), should return an error", test: func(t *testing.T) { @@ -242,7 +242,7 @@ func TestNewListOptionIndexer(t *testing.T) { } }) - _, err := NewListOptionIndexer(fields, store, true) + _, err := NewListOptionIndexer(context.Background(), fields, store, true) assert.NotNil(t, err) }}) @@ -962,7 +962,7 @@ func TestListByOptions(t *testing.T) { store.EXPECT().ReadInt(rows).Return(len(test.expectedList.Items), nil) store.EXPECT().CloseStmt(stmt).Return(nil) } - list, total, contToken, err := lii.executeQuery(context.TODO(), queryInfo) + list, total, contToken, err := lii.executeQuery(context.Background(), queryInfo) if test.expectedErr == nil { assert.Nil(t, err) } else { diff --git a/pkg/sqlcache/integration_test.go b/pkg/sqlcache/integration_test.go index 58715918..8c7e1ea7 100644 --- a/pkg/sqlcache/integration_test.go +++ b/pkg/sqlcache/integration_test.go @@ -323,7 +323,7 @@ func (i *IntegrationSuite) createCacheAndFactory(fields [][]string, transformFun Resource: "configmaps", } dynamicResource := dynamicClient.Resource(configMapGVR).Namespace(testNamespace) - cache, err := cacheFactory.CacheFor(fields, transformFunc, dynamicResource, configMapGVK, true, true) + cache, err := cacheFactory.CacheFor(context.Background(), fields, transformFunc, dynamicResource, configMapGVK, true, true) if err != nil { return nil, nil, fmt.Errorf("unable to make cache: %w", err) } diff --git a/pkg/sqlcache/store/store.go b/pkg/sqlcache/store/store.go index d76e0542..ab220a43 100644 --- a/pkg/sqlcache/store/store.go +++ b/pkg/sqlcache/store/store.go @@ -36,6 +36,7 @@ const ( type Store struct { db.Client + ctx context.Context name string typ reflect.Type keyFunc cache.KeyFunc @@ -61,8 +62,9 @@ type Store struct { var _ cache.Store = (*Store)(nil) // NewStore creates a SQLite-backed cache.Store for objects of the given example type -func NewStore(example any, keyFunc cache.KeyFunc, c db.Client, shouldEncrypt bool, name string) (*Store, error) { +func NewStore(ctx context.Context, example any, keyFunc cache.KeyFunc, c db.Client, shouldEncrypt bool, name string) (*Store, error) { s := &Store{ + ctx: ctx, name: name, typ: reflect.TypeOf(example), Client: c, @@ -75,7 +77,7 @@ func NewStore(example any, keyFunc cache.KeyFunc, c db.Client, shouldEncrypt boo dbName := db.Sanitize(s.name) // once multiple informerfactories are needed, this can accept the case where table already exists error is received - err := s.WithTransaction(context.Background(), true, func(tx transaction.Client) error { + err := s.WithTransaction(ctx, true, func(tx transaction.Client) error { createTableQuery := fmt.Sprintf(createTableFmt, dbName) _, err := tx.Exec(createTableQuery) if err != nil { @@ -106,7 +108,7 @@ func NewStore(example any, keyFunc cache.KeyFunc, c db.Client, shouldEncrypt boo /* Core methods */ // upsert saves an obj with its key, or updates key with obj if it exists in this Store func (s *Store) upsert(key string, obj any) error { - return s.WithTransaction(context.Background(), true, func(tx transaction.Client) error { + return s.WithTransaction(s.ctx, true, func(tx transaction.Client) error { err := s.Upsert(tx, s.upsertStmt, key, obj, s.shouldEncrypt) if err != nil { return &db.QueryError{QueryString: s.upsertQuery, Err: err} @@ -123,7 +125,7 @@ func (s *Store) upsert(key string, obj any) error { // deleteByKey deletes the object associated with key, if it exists in this Store func (s *Store) deleteByKey(key string) error { - return s.WithTransaction(context.Background(), true, func(tx transaction.Client) error { + return s.WithTransaction(s.ctx, true, func(tx transaction.Client) error { _, err := tx.Stmt(s.deleteStmt).Exec(key) if err != nil { return &db.QueryError{QueryString: s.deleteQuery, Err: err} @@ -140,7 +142,7 @@ func (s *Store) deleteByKey(key string) error { // GetByKey returns the object associated with the given object's key func (s *Store) GetByKey(key string) (item any, exists bool, err error) { - rows, err := s.QueryForRows(context.TODO(), s.getStmt, key) + rows, err := s.QueryForRows(s.ctx, s.getStmt, key) if err != nil { return nil, false, &db.QueryError{QueryString: s.getQuery, Err: err} } @@ -195,7 +197,7 @@ func (s *Store) Delete(obj any) error { // List returns a list of all the currently known objects // Note: I/O errors will panic this function, as the interface signature does not allow returning errors func (s *Store) List() []any { - rows, err := s.QueryForRows(context.TODO(), s.listStmt) + rows, err := s.QueryForRows(s.ctx, s.listStmt) if err != nil { panic(&db.QueryError{QueryString: s.listQuery, Err: err}) } @@ -210,7 +212,7 @@ func (s *Store) List() []any { // Note: Atm it doesn't appear returning nil in the case of an error has any detrimental effects. An error is not // uncommon enough nor does it appear to necessitate a panic. func (s *Store) ListKeys() []string { - rows, err := s.QueryForRows(context.TODO(), s.listKeysStmt) + rows, err := s.QueryForRows(s.ctx, s.listKeysStmt) if err != nil { fmt.Printf("Unexpected error in store.ListKeys: while executing query: %s got error: %v", s.listKeysQuery, err) return []string{} @@ -249,10 +251,10 @@ func (s *Store) Replace(objects []any, _ string) error { // replaceByKey will delete the contents of the Store, using instead the given key to obj map func (s *Store) replaceByKey(objects map[string]any) error { - return s.WithTransaction(context.Background(), true, func(txC transaction.Client) error { + return s.WithTransaction(s.ctx, true, func(txC transaction.Client) error { txCListKeys := txC.Stmt(s.listKeysStmt) - rows, err := s.QueryForRows(context.TODO(), txCListKeys) + rows, err := s.QueryForRows(s.ctx, txCListKeys) if err != nil { return err } diff --git a/pkg/sqlcache/store/store_test.go b/pkg/sqlcache/store/store_test.go index e1bff33b..e7db7045 100644 --- a/pkg/sqlcache/store/store_test.go +++ b/pkg/sqlcache/store/store_test.go @@ -362,7 +362,7 @@ func TestList(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.listStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listStmt).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return([]any{}, nil) items := store.List() assert.Len(t, items, 0) @@ -373,7 +373,7 @@ func TestList(t *testing.T) { store := SetupStore(t, c, shouldEncrypt) fakeItemsToReturn := []any{"something1", 2, false} r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.listStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listStmt).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return(fakeItemsToReturn, nil) items := store.List() assert.Equal(t, fakeItemsToReturn, items) @@ -383,7 +383,7 @@ func TestList(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.listStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listStmt).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return(nil, fmt.Errorf("error")) defer func() { recover() @@ -412,7 +412,7 @@ func TestListKeys(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return([]string{"a", "b", "c"}, nil) keys := store.ListKeys() assert.Len(t, keys, 3) @@ -423,7 +423,7 @@ func TestListKeys(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return(nil, fmt.Errorf("error")) keys := store.ListKeys() assert.Len(t, keys, 0) @@ -449,7 +449,7 @@ func TestGet(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return([]any{testObject}, nil) item, exists, err := store.Get(testObject) assert.Nil(t, err) @@ -461,7 +461,7 @@ func TestGet(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return([]any{}, nil) item, exists, err := store.Get(testObject) assert.Nil(t, err) @@ -473,7 +473,7 @@ func TestGet(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return(nil, fmt.Errorf("error")) _, _, err := store.Get(testObject) assert.NotNil(t, err) @@ -499,7 +499,7 @@ func TestGetByKey(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return([]any{testObject}, nil) item, exists, err := store.GetByKey(testObject.Id) assert.Nil(t, err) @@ -511,7 +511,7 @@ func TestGetByKey(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return([]any{}, nil) item, exists, err := store.GetByKey(testObject.Id) assert.Nil(t, err) @@ -523,7 +523,7 @@ func TestGetByKey(t *testing.T) { c, _ := SetupMockDB(t) store := SetupStore(t, c, shouldEncrypt) r := &sql.Rows{} - c.EXPECT().QueryForRows(context.TODO(), store.getStmt, testObject.Id).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.getStmt, testObject.Id).Return(r, nil) c.EXPECT().ReadObjects(r, reflect.TypeOf(testObject), store.shouldEncrypt).Return(nil, fmt.Errorf("error")) _, _, err := store.GetByKey(testObject.Id) assert.NotNil(t, err) @@ -554,7 +554,7 @@ func TestReplace(t *testing.T) { stmt := NewMockStmt(gomock.NewController(t)) txC.EXPECT().Stmt(store.listKeysStmt).Return(stmt) - c.EXPECT().QueryForRows(context.TODO(), stmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), stmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return([]string{testObject.Id}, nil) txC.EXPECT().Stmt(store.deleteStmt).Return(stmt) stmt.EXPECT().Exec(testObject.Id) @@ -578,7 +578,7 @@ func TestReplace(t *testing.T) { r := &sql.Rows{} txC.EXPECT().Stmt(store.listKeysStmt).Return(store.listKeysStmt) - c.EXPECT().QueryForRows(context.TODO(), store.listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return([]string{}, nil) c.EXPECT().Upsert(txC, store.upsertStmt, testObject.Id, testObject, store.shouldEncrypt) @@ -608,7 +608,7 @@ func TestReplace(t *testing.T) { r := &sql.Rows{} txC.EXPECT().Stmt(store.listKeysStmt).Return(store.listKeysStmt) - c.EXPECT().QueryForRows(context.TODO(), store.listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), store.listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return(nil, fmt.Errorf("error")) c.EXPECT().WithTransaction(gomock.Any(), true, gomock.Any()).Return(fmt.Errorf("error")).Do( @@ -631,7 +631,7 @@ func TestReplace(t *testing.T) { deleteStmt := NewMockStmt(gomock.NewController(t)) txC.EXPECT().Stmt(store.listKeysStmt).Return(listKeysStmt) - c.EXPECT().QueryForRows(context.TODO(), listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return([]string{testObject.Id}, nil) txC.EXPECT().Stmt(store.deleteStmt).Return(deleteStmt) deleteStmt.EXPECT().Exec(testObject.Id).Return(nil, fmt.Errorf("error")) @@ -655,7 +655,7 @@ func TestReplace(t *testing.T) { deleteStmt := NewMockStmt(gomock.NewController(t)) txC.EXPECT().Stmt(store.listKeysStmt).Return(listKeysStmt) - c.EXPECT().QueryForRows(context.TODO(), listKeysStmt).Return(r, nil) + c.EXPECT().QueryForRows(context.Background(), listKeysStmt).Return(r, nil) c.EXPECT().ReadStrings(r).Return([]string{testObject.Id}, nil) txC.EXPECT().Stmt(store.deleteStmt).Return(deleteStmt) deleteStmt.EXPECT().Exec(testObject.Id).Return(nil, nil) @@ -726,7 +726,7 @@ func SetupMockDB(t *testing.T) (*MockClient, *MockTXClient) { return dbC, txC } func SetupStore(t *testing.T, client *MockClient, shouldEncrypt bool) *Store { - store, err := NewStore(testStoreObject{}, testStoreKeyFunc, client, shouldEncrypt, "testStoreObject") + store, err := NewStore(context.Background(), testStoreObject{}, testStoreKeyFunc, client, shouldEncrypt, "testStoreObject") if err != nil { t.Error(err) } diff --git a/pkg/stores/sqlproxy/proxy_mocks_test.go b/pkg/stores/sqlproxy/proxy_mocks_test.go index 45ccd418..3aeee7e5 100644 --- a/pkg/stores/sqlproxy/proxy_mocks_test.go +++ b/pkg/stores/sqlproxy/proxy_mocks_test.go @@ -263,18 +263,18 @@ func (m *MockCacheFactory) EXPECT() *MockCacheFactoryMockRecorder { } // CacheFor mocks base method. -func (m *MockCacheFactory) CacheFor(arg0 [][]string, arg1 cache.TransformFunc, arg2 dynamic.ResourceInterface, arg3 schema.GroupVersionKind, arg4, arg5 bool) (factory.Cache, error) { +func (m *MockCacheFactory) CacheFor(arg0 context.Context, arg1 [][]string, arg2 cache.TransformFunc, arg3 dynamic.ResourceInterface, arg4 schema.GroupVersionKind, arg5, arg6 bool) (factory.Cache, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CacheFor", arg0, arg1, arg2, arg3, arg4, arg5) + ret := m.ctrl.Call(m, "CacheFor", arg0, arg1, arg2, arg3, arg4, arg5, arg6) ret0, _ := ret[0].(factory.Cache) ret1, _ := ret[1].(error) return ret0, ret1 } // CacheFor indicates an expected call of CacheFor. -func (mr *MockCacheFactoryMockRecorder) CacheFor(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { +func (mr *MockCacheFactoryMockRecorder) CacheFor(arg0, arg1, arg2, arg3, arg4, arg5, arg6 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CacheFor", reflect.TypeOf((*MockCacheFactory)(nil).CacheFor), arg0, arg1, arg2, arg3, arg4, arg5) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CacheFor", reflect.TypeOf((*MockCacheFactory)(nil).CacheFor), arg0, arg1, arg2, arg3, arg4, arg5, arg6) } // Reset mocks base method. diff --git a/pkg/stores/sqlproxy/proxy_store.go b/pkg/stores/sqlproxy/proxy_store.go index 30ad73c7..f2849970 100644 --- a/pkg/stores/sqlproxy/proxy_store.go +++ b/pkg/stores/sqlproxy/proxy_store.go @@ -221,6 +221,7 @@ type TransformBuilder interface { } type Store struct { + ctx context.Context clientGetter ClientGetter notifier RelationshipNotifier cacheFactory CacheFactory @@ -234,13 +235,14 @@ type Store struct { type CacheFactoryInitializer func() (CacheFactory, error) type CacheFactory interface { - CacheFor(fields [][]string, transform cache.TransformFunc, client dynamic.ResourceInterface, gvk schema.GroupVersionKind, namespaced bool, watchable bool) (factory.Cache, error) + CacheFor(ctx context.Context, fields [][]string, transform cache.TransformFunc, client dynamic.ResourceInterface, gvk schema.GroupVersionKind, namespaced bool, watchable bool) (factory.Cache, error) Reset() error } // NewProxyStore returns a Store implemented directly on top of kubernetes. -func NewProxyStore(c SchemaColumnSetter, clientGetter ClientGetter, notifier RelationshipNotifier, scache virtualCommon.SummaryCache, factory CacheFactory) (*Store, error) { +func NewProxyStore(ctx context.Context, c SchemaColumnSetter, clientGetter ClientGetter, notifier RelationshipNotifier, scache virtualCommon.SummaryCache, factory CacheFactory) (*Store, error) { store := &Store{ + ctx: ctx, clientGetter: clientGetter, notifier: notifier, columnSetter: c, @@ -291,7 +293,7 @@ func (s *Store) initializeNamespaceCache() error { nsSchema := baseNSSchema // make sure any relevant columns are set to the ns schema - if err := s.columnSetter.SetColumns(context.Background(), &nsSchema); err != nil { + if err := s.columnSetter.SetColumns(s.ctx, &nsSchema); err != nil { return fmt.Errorf("failed to set columns for proxy stores namespace informer: %w", err) } @@ -314,7 +316,7 @@ func (s *Store) initializeNamespaceCache() error { // get the ns informer tableClient := &tablelistconvert.Client{ResourceInterface: client} attrs := attributes.GVK(&nsSchema) - nsInformer, err := s.cacheFactory.CacheFor(fields, transformFunc, tableClient, attrs, false, true) + nsInformer, err := s.cacheFactory.CacheFor(s.ctx, fields, transformFunc, tableClient, attrs, false, true) if err != nil { return err } @@ -756,7 +758,7 @@ func (s *Store) ListByPartitions(apiOp *types.APIRequest, schema *types.APISchem tableClient := &tablelistconvert.Client{ResourceInterface: client} attrs := attributes.GVK(schema) ns := attributes.Namespaced(schema) - inf, err := s.cacheFactory.CacheFor(fields, transformFunc, tableClient, attrs, ns, controllerschema.IsListWatchable(schema)) + inf, err := s.cacheFactory.CacheFor(s.ctx, fields, transformFunc, tableClient, attrs, ns, controllerschema.IsListWatchable(schema)) if err != nil { return nil, 0, "", err } diff --git a/pkg/stores/sqlproxy/proxy_store_test.go b/pkg/stores/sqlproxy/proxy_store_test.go index 8690eea3..94026f30 100644 --- a/pkg/stores/sqlproxy/proxy_store_test.go +++ b/pkg/stores/sqlproxy/proxy_store_test.go @@ -12,11 +12,11 @@ import ( "github.com/rancher/wrangler/v3/pkg/schemas/validation" apierrors "k8s.io/apimachinery/pkg/api/errors" + "github.com/rancher/steve/pkg/attributes" + "github.com/rancher/steve/pkg/resources/common" "github.com/rancher/steve/pkg/sqlcache/informer" "github.com/rancher/steve/pkg/sqlcache/informer/factory" "github.com/rancher/steve/pkg/sqlcache/partition" - "github.com/rancher/steve/pkg/attributes" - "github.com/rancher/steve/pkg/resources/common" "github.com/rancher/steve/pkg/stores/sqlpartition/listprocessor" "github.com/rancher/steve/pkg/stores/sqlproxy/tablelistconvert" "go.uber.org/mock/gomock" @@ -82,9 +82,9 @@ func TestNewProxyStore(t *testing.T) { nsSchema := baseNSSchema scc.EXPECT().SetColumns(context.Background(), &nsSchema).Return(nil) cg.EXPECT().TableAdminClient(nil, &nsSchema, "", &WarningBuffer{}).Return(ri, nil) - cf.EXPECT().CacheFor([][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(c, nil) + cf.EXPECT().CacheFor(context.Background(), [][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(c, nil) - s, err := NewProxyStore(scc, cg, rn, nil, cf) + s, err := NewProxyStore(context.Background(), scc, cg, rn, nil, cf) assert.Nil(t, err) assert.Equal(t, scc, s.columnSetter) assert.Equal(t, cg, s.clientGetter) @@ -105,7 +105,7 @@ func TestNewProxyStore(t *testing.T) { nsSchema := baseNSSchema scc.EXPECT().SetColumns(context.Background(), &nsSchema).Return(fmt.Errorf("error")) - s, err := NewProxyStore(scc, cg, rn, nil, cf) + s, err := NewProxyStore(context.Background(), scc, cg, rn, nil, cf) assert.Nil(t, err) assert.Equal(t, scc, s.columnSetter) assert.Equal(t, cg, s.clientGetter) @@ -127,7 +127,7 @@ func TestNewProxyStore(t *testing.T) { scc.EXPECT().SetColumns(context.Background(), &nsSchema).Return(nil) cg.EXPECT().TableAdminClient(nil, &nsSchema, "", &WarningBuffer{}).Return(nil, fmt.Errorf("error")) - s, err := NewProxyStore(scc, cg, rn, nil, cf) + s, err := NewProxyStore(context.Background(), scc, cg, rn, nil, cf) assert.Nil(t, err) assert.Equal(t, scc, s.columnSetter) assert.Equal(t, cg, s.clientGetter) @@ -149,9 +149,9 @@ func TestNewProxyStore(t *testing.T) { nsSchema := baseNSSchema scc.EXPECT().SetColumns(context.Background(), &nsSchema).Return(nil) cg.EXPECT().TableAdminClient(nil, &nsSchema, "", &WarningBuffer{}).Return(ri, nil) - cf.EXPECT().CacheFor([][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(factory.Cache{}, fmt.Errorf("error")) + cf.EXPECT().CacheFor(context.Background(), [][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(factory.Cache{}, fmt.Errorf("error")) - s, err := NewProxyStore(scc, cg, rn, nil, cf) + s, err := NewProxyStore(context.Background(), scc, cg, rn, nil, cf) assert.Nil(t, err) assert.Equal(t, scc, s.columnSetter) assert.Equal(t, cg, s.clientGetter) @@ -189,6 +189,7 @@ func TestListByPartitions(t *testing.T) { ByOptionsLister: inf, } s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -241,7 +242,7 @@ func TestListByPartitions(t *testing.T) { assert.Nil(t, err) cg.EXPECT().TableAdminClient(req, schema, "", &WarningBuffer{}).Return(ri, nil) // This tests that fields are being extracted from schema columns and the type specific fields map - cf.EXPECT().CacheFor([][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(c, nil) + cf.EXPECT().CacheFor(context.Background(), [][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(c, nil) tb.EXPECT().GetTransformFunc(attributes.GVK(schema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) bloi.EXPECT().ListByOptions(req.Context(), opts, partitions, req.Namespace).Return(listToReturn, len(listToReturn.Items), "", nil) list, total, contToken, err := s.ListByPartitions(req, schema, partitions) @@ -260,6 +261,7 @@ func TestListByPartitions(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -327,6 +329,7 @@ func TestListByPartitions(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -399,6 +402,7 @@ func TestListByPartitions(t *testing.T) { ByOptionsLister: inf, } s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -454,7 +458,7 @@ func TestListByPartitions(t *testing.T) { // This tests that fields are being extracted from schema columns and the type specific fields map // note also the watchable bool is expected to be false - cf.EXPECT().CacheFor([][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), false).Return(c, nil) + cf.EXPECT().CacheFor(context.Background(), [][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), false).Return(c, nil) tb.EXPECT().GetTransformFunc(attributes.GVK(schema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) bloi.EXPECT().ListByOptions(req.Context(), opts, partitions, req.Namespace).Return(listToReturn, len(listToReturn.Items), "", nil) @@ -475,6 +479,7 @@ func TestListByPartitions(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -528,7 +533,7 @@ func TestListByPartitions(t *testing.T) { cg.EXPECT().TableAdminClient(req, schema, "", &WarningBuffer{}).Return(ri, nil) // This tests that fields are being extracted from schema columns and the type specific fields map tb.EXPECT().GetTransformFunc(attributes.GVK(schema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) - cf.EXPECT().CacheFor([][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(factory.Cache{}, fmt.Errorf("error")) + cf.EXPECT().CacheFor(context.Background(), [][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(factory.Cache{}, fmt.Errorf("error")) _, _, _, err = s.ListByPartitions(req, schema, partitions) assert.NotNil(t, err) @@ -551,6 +556,7 @@ func TestListByPartitions(t *testing.T) { ByOptionsLister: inf, } s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -603,7 +609,7 @@ func TestListByPartitions(t *testing.T) { assert.Nil(t, err) cg.EXPECT().TableAdminClient(req, schema, "", &WarningBuffer{}).Return(ri, nil) // This tests that fields are being extracted from schema columns and the type specific fields map - cf.EXPECT().CacheFor([][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(c, nil) + cf.EXPECT().CacheFor(context.Background(), [][]string{{"some", "field"}, {`id`}, {`metadata`, `state`, `name`}, {"gvk", "specific", "fields"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(schema), attributes.Namespaced(schema), true).Return(c, nil) bloi.EXPECT().ListByOptions(req.Context(), opts, partitions, req.Namespace).Return(nil, 0, "", fmt.Errorf("error")) tb.EXPECT().GetTransformFunc(attributes.GVK(schema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) @@ -634,6 +640,7 @@ func TestReset(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) nsc2 := factory.Cache{} s := &Store{ + ctx: context.Background(), namespaceCache: nsc, clientGetter: cg, cacheFactory: cf, @@ -645,7 +652,7 @@ func TestReset(t *testing.T) { cf.EXPECT().Reset().Return(nil) cs.EXPECT().SetColumns(gomock.Any(), gomock.Any()).Return(nil) cg.EXPECT().TableAdminClient(nil, &nsSchema, "", &WarningBuffer{}).Return(ri, nil) - cf.EXPECT().CacheFor([][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(nsc2, nil) + cf.EXPECT().CacheFor(context.Background(), [][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(nsc2, nil) tb.EXPECT().GetTransformFunc(attributes.GVK(&nsSchema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) err := s.Reset() assert.Nil(t, err) @@ -662,6 +669,7 @@ func TestReset(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -685,6 +693,7 @@ func TestReset(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -709,6 +718,7 @@ func TestReset(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsi, clientGetter: cg, cacheFactory: cf, @@ -736,6 +746,7 @@ func TestReset(t *testing.T) { tb := NewMockTransformBuilder(gomock.NewController(t)) s := &Store{ + ctx: context.Background(), namespaceCache: nsc, clientGetter: cg, cacheFactory: cf, @@ -748,7 +759,7 @@ func TestReset(t *testing.T) { cf.EXPECT().Reset().Return(nil) cs.EXPECT().SetColumns(gomock.Any(), gomock.Any()).Return(nil) cg.EXPECT().TableAdminClient(nil, &nsSchema, "", &WarningBuffer{}).Return(ri, nil) - cf.EXPECT().CacheFor([][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(factory.Cache{}, fmt.Errorf("error")) + cf.EXPECT().CacheFor(context.Background(), [][]string{{`id`}, {`metadata`, `state`, `name`}, {"metadata", "labels[field.cattle.io/projectId]"}}, gomock.Any(), &tablelistconvert.Client{ResourceInterface: ri}, attributes.GVK(&nsSchema), false, true).Return(factory.Cache{}, fmt.Errorf("error")) tb.EXPECT().GetTransformFunc(attributes.GVK(&nsSchema)).Return(func(obj interface{}) (interface{}, error) { return obj, nil }) err := s.Reset() assert.NotNil(t, err)