From f2b46d4c8ba8d23baff86ed085d4519e6ccb0415 Mon Sep 17 00:00:00 2001 From: FlamingSaint <78465537+FlamingSaint@users.noreply.github.com> Date: Mon, 3 Jun 2024 07:58:09 +0530 Subject: [PATCH] Enable Lint Rule: use-any (#5510) --- .golangci.yml | 3 -- cmd/agent/app/processors/thrift_processor.go | 2 +- cmd/agent/app/reporter/client_metrics.go | 2 +- cmd/agent/app/reporter/grpc/builder_test.go | 2 +- cmd/agent/app/servers/tbuffered_server.go | 2 +- cmd/anonymizer/app/uiconv/extractor_test.go | 2 +- cmd/collector/app/metrics.go | 2 +- cmd/collector/app/span_processor.go | 4 +- cmd/es-rollover/app/init/action.go | 4 +- cmd/es-rollover/app/rollover/action.go | 2 +- cmd/es-rollover/app/rollover/action_test.go | 10 ++--- .../app/renderer/render_test.go | 2 +- cmd/internal/flags/admin_test.go | 2 +- cmd/internal/flags/service_test.go | 8 ++-- .../internal/integration/e2e_integration.go | 20 +++++----- cmd/query/app/apiv3/gateway_test.go | 2 +- cmd/query/app/apiv3/http_gateway.go | 2 +- cmd/query/app/grpc_handler.go | 2 +- cmd/query/app/grpc_handler_test.go | 4 +- cmd/query/app/handler_deps_test.go | 4 +- cmd/query/app/http_handler.go | 10 ++--- cmd/query/app/http_handler_test.go | 26 ++++++------- cmd/query/app/json_marshaler.go | 8 ++-- cmd/query/app/static_handler.go | 2 +- cmd/query/app/static_handler_test.go | 6 +-- examples/hotrod/pkg/log/spanlogger.go | 4 +- examples/hotrod/pkg/tracing/http.go | 2 +- examples/hotrod/services/frontend/server.go | 2 +- internal/metricstest/local_test.go | 2 +- model/converter/json/from_domain.go | 2 +- model/converter/json/from_domain_test.go | 2 +- .../converter/thrift/jaeger/to_domain_test.go | 2 +- model/converter/thrift/zipkin/to_domain.go | 2 +- .../converter/thrift/zipkin/to_domain_test.go | 4 +- model/json/model.go | 6 +-- model/keyvalue.go | 4 +- model/keyvalue_test.go | 2 +- pkg/cache/cache.go | 8 ++-- pkg/cache/lru.go | 10 ++--- pkg/cache/lru_test.go | 6 +-- pkg/cassandra/gocql/gocql.go | 8 ++-- pkg/cassandra/metrics/table_test.go | 2 +- pkg/cassandra/session.go | 8 ++-- pkg/es/client.go | 2 +- pkg/es/client/cluster_client.go | 4 +- pkg/es/client/index_client.go | 16 ++++---- pkg/es/client/index_client_test.go | 2 +- pkg/es/client/interfaces.go | 2 +- pkg/es/textTemplate.go | 2 +- pkg/es/wrapper/wrapper_nolint.go | 2 +- pkg/fswatcher/fswatcher_test.go | 4 +- pkg/gogocodec/codec.go | 4 +- pkg/gzipfs/gzip.go | 2 +- pkg/metrics/metrics.go | 6 +-- pkg/queue/bounded_queue.go | 20 +++++----- pkg/queue/bounded_queue_test.go | 36 +++++++++--------- pkg/recoveryhandler/zap.go | 2 +- pkg/tenancy/grpc.go | 6 +-- pkg/tenancy/grpc_test.go | 6 +-- .../distributedlock/cassandra/lock_test.go | 20 +++++----- .../cassandra/dependencystore/storage_test.go | 12 +++--- .../cassandra/samplingstore/storage_test.go | 20 +++++----- .../cassandra/spanstore/matchers_test.go | 12 +++--- .../spanstore/operation_names_test.go | 12 +++--- .../cassandra/spanstore/reader_test.go | 10 ++--- .../cassandra/spanstore/service_names_test.go | 12 +++--- .../es/dependencystore/storage_test.go | 12 +++--- .../storage/es/samplingstore/storage_test.go | 2 +- .../es/spanstore/dbmodel/from_domain.go | 6 +-- .../es/spanstore/dbmodel/from_domain_test.go | 4 +- plugin/storage/es/spanstore/dbmodel/model.go | 14 +++---- .../storage/es/spanstore/dbmodel/to_domain.go | 4 +- .../es/spanstore/dbmodel/to_domain_test.go | 36 +++++++++--------- plugin/storage/es/spanstore/reader_test.go | 38 +++++++++---------- plugin/storage/es/spanstore/writer_test.go | 10 ++--- plugin/storage/integration/integration.go | 2 +- storage/spanstore/downsampling_writer.go | 2 +- 77 files changed, 275 insertions(+), 278 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7ca9b4b8fb9..32237518db1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -169,9 +169,6 @@ linters-settings: - name: cyclomatic disabled: true # do a clean-up and enable - - name: use-any - disabled: true - # do a clean-up and enable - name: unused-parameter disabled: true # do a clean-up and enable diff --git a/cmd/agent/app/processors/thrift_processor.go b/cmd/agent/app/processors/thrift_processor.go index f16aea5cd86..0045388994f 100644 --- a/cmd/agent/app/processors/thrift_processor.go +++ b/cmd/agent/app/processors/thrift_processor.go @@ -67,7 +67,7 @@ func NewThriftProcessor( "number of processors must be greater than 0, called with %d", numProcessors) } protocolPool := &sync.Pool{ - New: func() interface{} { + New: func() any { trans := &customtransport.TBufferedReadTransport{} return factory.GetProtocol(trans) }, diff --git a/cmd/agent/app/reporter/client_metrics.go b/cmd/agent/app/reporter/client_metrics.go index c93b60f0b38..4213c1929ef 100644 --- a/cmd/agent/app/reporter/client_metrics.go +++ b/cmd/agent/app/reporter/client_metrics.go @@ -143,7 +143,7 @@ func (r *ClientMetricsReporter) expireClientMetricsLoop() { func (r *ClientMetricsReporter) expireClientMetrics(t time.Time) { var size int64 - r.lastReceivedClientStats.Range(func(k, v interface{}) bool { + r.lastReceivedClientStats.Range(func(k, v any) bool { stats := v.(*lastReceivedClientStats) stats.lock.Lock() defer stats.lock.Unlock() diff --git a/cmd/agent/app/reporter/grpc/builder_test.go b/cmd/agent/app/reporter/grpc/builder_test.go index d241cd350e4..18ae28df95f 100644 --- a/cmd/agent/app/reporter/grpc/builder_test.go +++ b/cmd/agent/app/reporter/grpc/builder_test.go @@ -369,7 +369,7 @@ type fakeInterceptor struct { isCalled bool } -func (f *fakeInterceptor) intercept(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { +func (f *fakeInterceptor) intercept(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { f.isCalled = true return invoker(ctx, method, req, reply, cc, opts...) } diff --git a/cmd/agent/app/servers/tbuffered_server.go b/cmd/agent/app/servers/tbuffered_server.go index 6a9d49b45ad..f52a0fa6fea 100644 --- a/cmd/agent/app/servers/tbuffered_server.go +++ b/cmd/agent/app/servers/tbuffered_server.go @@ -79,7 +79,7 @@ func NewTBufferedServer( dataChan := make(chan *ReadBuf, maxQueueSize) readBufPool := &sync.Pool{ - New: func() interface{} { + New: func() any { return &ReadBuf{bytes: make([]byte, maxPacketSize)} }, } diff --git a/cmd/anonymizer/app/uiconv/extractor_test.go b/cmd/anonymizer/app/uiconv/extractor_test.go index 5ee27de68b6..15fdac11a25 100644 --- a/cmd/anonymizer/app/uiconv/extractor_test.go +++ b/cmd/anonymizer/app/uiconv/extractor_test.go @@ -100,7 +100,7 @@ func TestExtractorTraceScanError(t *testing.T) { require.Contains(t, err.Error(), "failed when scanning the file") } -func loadJSON(t *testing.T, fileName string, i interface{}) { +func loadJSON(t *testing.T, fileName string, i any) { b, err := os.ReadFile(fileName) require.NoError(t, err) err = json.Unmarshal(b, i) diff --git a/cmd/collector/app/metrics.go b/cmd/collector/app/metrics.go index f0a929c0ebe..8602507b7da 100644 --- a/cmd/collector/app/metrics.go +++ b/cmd/collector/app/metrics.go @@ -169,7 +169,7 @@ func newTraceCountsBySvc(factory metrics.Factory, category string, maxServices i }, // use sync.Pool to reduce allocation of stringBuilder stringBuilderPool: &sync.Pool{ - New: func() interface{} { + New: func() any { return new(strings.Builder) }, }, diff --git a/cmd/collector/app/span_processor.go b/cmd/collector/app/span_processor.go index fff5dae06e4..03d9ae460dd 100644 --- a/cmd/collector/app/span_processor.go +++ b/cmd/collector/app/span_processor.go @@ -73,7 +73,7 @@ func NewSpanProcessor( ) processor.SpanProcessor { sp := newSpanProcessor(spanWriter, additional, opts...) - sp.queue.StartConsumers(sp.numWorkers, func(item interface{}) { + sp.queue.StartConsumers(sp.numWorkers, func(item any) { value := item.(*queueItem) sp.processItemFromQueue(value) }) @@ -93,7 +93,7 @@ func newSpanProcessor(spanWriter spanstore.Writer, additional []ProcessSpan, opt options.serviceMetrics, options.hostMetrics, options.extraFormatTypes) - droppedItemHandler := func(item interface{}) { + droppedItemHandler := func(item any) { handlerMetrics.SpansDropped.Inc(1) if options.onDroppedSpan != nil { options.onDroppedSpan(item.(*queueItem).span) diff --git a/cmd/es-rollover/app/init/action.go b/cmd/es-rollover/app/init/action.go index 28ee6dea2d5..d0b982125bc 100644 --- a/cmd/es-rollover/app/init/action.go +++ b/cmd/es-rollover/app/init/action.go @@ -92,13 +92,13 @@ func createIndexIfNotExist(c client.IndexAPI, index string) error { return esErr.Err } // check for the reason of the error - jsonError := map[string]interface{}{} + jsonError := map[string]any{} err := json.Unmarshal(esErr.Body, &jsonError) if err != nil { // return unmarshal error return err } - errorMap := jsonError["error"].(map[string]interface{}) + errorMap := jsonError["error"].(map[string]any) // check for reason, ignore already exist error if strings.Contains(errorMap["type"].(string), "resource_already_exists_exception") { return nil diff --git a/cmd/es-rollover/app/rollover/action.go b/cmd/es-rollover/app/rollover/action.go index 594a488f0f3..39ef2a4f8cb 100644 --- a/cmd/es-rollover/app/rollover/action.go +++ b/cmd/es-rollover/app/rollover/action.go @@ -40,7 +40,7 @@ func (a *Action) Do() error { } func (a *Action) rollover(indexSet app.IndexOption) error { - conditionsMap := map[string]interface{}{} + conditionsMap := map[string]any{} if len(a.Conditions) > 0 { err := json.Unmarshal([]byte(a.Config.Conditions), &conditionsMap) if err != nil { diff --git a/cmd/es-rollover/app/rollover/action_test.go b/cmd/es-rollover/app/rollover/action_test.go index 09c272420ed..9aa760ed256 100644 --- a/cmd/es-rollover/app/rollover/action_test.go +++ b/cmd/es-rollover/app/rollover/action_test.go @@ -57,7 +57,7 @@ func TestRolloverAction(t *testing.T) { setupCallExpectations: func(indexClient *mocks.MockIndexAPI, test *testCase) { indexClient.On("GetJaegerIndices", "").Return(test.indices, test.getJaegerIndicesErr) indexClient.On("CreateAlias", aliasToCreate).Return(test.createAliasErr) - indexClient.On("Rollover", "jaeger-span-archive-write", map[string]interface{}{"max_age": "2d"}).Return(test.rolloverErr) + indexClient.On("Rollover", "jaeger-span-archive-write", map[string]any{"max_age": "2d"}).Return(test.rolloverErr) }, }, { @@ -74,7 +74,7 @@ func TestRolloverAction(t *testing.T) { }, setupCallExpectations: func(indexClient *mocks.MockIndexAPI, test *testCase) { indexClient.On("GetJaegerIndices", "").Return(test.indices, test.getJaegerIndicesErr) - indexClient.On("Rollover", "jaeger-span-archive-write", map[string]interface{}{"max_age": "2d"}).Return(test.rolloverErr) + indexClient.On("Rollover", "jaeger-span-archive-write", map[string]any{"max_age": "2d"}).Return(test.rolloverErr) }, }, { @@ -84,7 +84,7 @@ func TestRolloverAction(t *testing.T) { getJaegerIndicesErr: errors.New("unable to get indices"), indices: readIndices, setupCallExpectations: func(indexClient *mocks.MockIndexAPI, test *testCase) { - indexClient.On("Rollover", "jaeger-span-archive-write", map[string]interface{}{"max_age": "2d"}).Return(test.rolloverErr) + indexClient.On("Rollover", "jaeger-span-archive-write", map[string]any{"max_age": "2d"}).Return(test.rolloverErr) indexClient.On("GetJaegerIndices", "").Return(test.indices, test.getJaegerIndicesErr) }, }, @@ -95,7 +95,7 @@ func TestRolloverAction(t *testing.T) { rolloverErr: errors.New("unable to rollover"), indices: readIndices, setupCallExpectations: func(indexClient *mocks.MockIndexAPI, test *testCase) { - indexClient.On("Rollover", "jaeger-span-archive-write", map[string]interface{}{"max_age": "2d"}).Return(test.rolloverErr) + indexClient.On("Rollover", "jaeger-span-archive-write", map[string]any{"max_age": "2d"}).Return(test.rolloverErr) }, }, { @@ -107,7 +107,7 @@ func TestRolloverAction(t *testing.T) { setupCallExpectations: func(indexClient *mocks.MockIndexAPI, test *testCase) { indexClient.On("GetJaegerIndices", "").Return(test.indices, test.getJaegerIndicesErr) indexClient.On("CreateAlias", aliasToCreate).Return(test.createAliasErr) - indexClient.On("Rollover", "jaeger-span-archive-write", map[string]interface{}{"max_age": "2d"}).Return(test.rolloverErr) + indexClient.On("Rollover", "jaeger-span-archive-write", map[string]any{"max_age": "2d"}).Return(test.rolloverErr) }, }, { diff --git a/cmd/esmapping-generator/app/renderer/render_test.go b/cmd/esmapping-generator/app/renderer/render_test.go index e8245b24696..e3e43f4beb7 100644 --- a/cmd/esmapping-generator/app/renderer/render_test.go +++ b/cmd/esmapping-generator/app/renderer/render_test.go @@ -70,7 +70,7 @@ func Test_getMappingAsString(t *testing.T) { // Prepare mockTemplateApplier := &mocks.TemplateApplier{} mockTemplateApplier.On("Execute", mock.Anything, mock.Anything).Return( - func(wr io.Writer, data interface{}) error { + func(wr io.Writer, data any) error { wr.Write([]byte(tt.want)) return nil }, diff --git a/cmd/internal/flags/admin_test.go b/cmd/internal/flags/admin_test.go index 6398848c1c4..52b58b87a7a 100644 --- a/cmd/internal/flags/admin_test.go +++ b/cmd/internal/flags/admin_test.go @@ -81,7 +81,7 @@ func TestAdminFailToServe(t *testing.T) { adminServer.serveWithListener(l) defer adminServer.Close() - waitForEqual(t, healthcheck.Broken, func() interface{} { return adminServer.HC().Get() }) + waitForEqual(t, healthcheck.Broken, func() any { return adminServer.HC().Get() }) logEntries := logs.TakeAll() var matchedEntry string diff --git a/cmd/internal/flags/service_test.go b/cmd/internal/flags/service_test.go index 9c4ec76fd37..0eaf8a10325 100644 --- a/cmd/internal/flags/service_test.go +++ b/cmd/internal/flags/service_test.go @@ -92,17 +92,17 @@ func TestStartErrors(t *testing.T) { } go s.RunAndThen(shutdown) - waitForEqual(t, healthcheck.Ready, func() interface{} { return s.HC().Get() }) + waitForEqual(t, healthcheck.Ready, func() any { return s.HC().Get() }) s.HC().Set(healthcheck.Unavailable) - waitForEqual(t, healthcheck.Unavailable, func() interface{} { return s.HC().Get() }) + waitForEqual(t, healthcheck.Unavailable, func() any { return s.HC().Get() }) s.signalsChannel <- os.Interrupt - waitForEqual(t, true, func() interface{} { return stopped.Load() }) + waitForEqual(t, true, func() any { return stopped.Load() }) }) } } -func waitForEqual(t *testing.T, expected interface{}, getter func() interface{}) { +func waitForEqual(t *testing.T, expected any, getter func() any) { for i := 0; i < 1000; i++ { value := getter() if reflect.DeepEqual(value, expected) { diff --git a/cmd/jaeger/internal/integration/e2e_integration.go b/cmd/jaeger/internal/integration/e2e_integration.go index 0cc7818d266..9b803050904 100644 --- a/cmd/jaeger/internal/integration/e2e_integration.go +++ b/cmd/jaeger/internal/integration/e2e_integration.go @@ -127,36 +127,36 @@ func (s *E2EStorageIntegration) e2eCleanUp(t *testing.T) { func createStorageCleanerConfig(t *testing.T, configFile string, storage string) string { data, err := os.ReadFile(configFile) require.NoError(t, err) - var config map[string]interface{} + var config map[string]any err = yaml.Unmarshal(data, &config) require.NoError(t, err) - service, ok := config["service"].(map[string]interface{}) + service, ok := config["service"].(map[string]any) require.True(t, ok) - service["extensions"] = append(service["extensions"].([]interface{}), "storage_cleaner") + service["extensions"] = append(service["extensions"].([]any), "storage_cleaner") - extensions, ok := config["extensions"].(map[string]interface{}) + extensions, ok := config["extensions"].(map[string]any) require.True(t, ok) - query, ok := extensions["jaeger_query"].(map[string]interface{}) + query, ok := extensions["jaeger_query"].(map[string]any) require.True(t, ok) trace_storage := query["trace_storage"].(string) extensions["storage_cleaner"] = map[string]string{"trace_storage": trace_storage} - jaegerStorage, ok := extensions["jaeger_storage"].(map[string]interface{}) + jaegerStorage, ok := extensions["jaeger_storage"].(map[string]any) require.True(t, ok) switch storage { case "elasticsearch": - elasticsearch, ok := jaegerStorage["elasticsearch"].(map[string]interface{}) + elasticsearch, ok := jaegerStorage["elasticsearch"].(map[string]any) require.True(t, ok) - esMain, ok := elasticsearch["es_main"].(map[string]interface{}) + esMain, ok := elasticsearch["es_main"].(map[string]any) require.True(t, ok) esMain["service_cache_ttl"] = "1ms" case "opensearch": - opensearch, ok := jaegerStorage["opensearch"].(map[string]interface{}) + opensearch, ok := jaegerStorage["opensearch"].(map[string]any) require.True(t, ok) - osMain, ok := opensearch["os_main"].(map[string]interface{}) + osMain, ok := opensearch["os_main"].(map[string]any) require.True(t, ok) osMain["service_cache_ttl"] = "1ms" diff --git a/cmd/query/app/apiv3/gateway_test.go b/cmd/query/app/apiv3/gateway_test.go index 66b0e600f34..799962388b0 100644 --- a/cmd/query/app/apiv3/gateway_test.go +++ b/cmd/query/app/apiv3/gateway_test.go @@ -72,7 +72,7 @@ func (gw *testGateway) execRequest(t *testing.T, url string) ([]byte, int) { func (gw *testGateway) verifySnapshot(t *testing.T, body []byte) []byte { // reformat JSON body with indentation, to make diffing easier - var data interface{} + var data any require.NoError(t, json.Unmarshal(body, &data), "response: %s", string(body)) body, err := json.MarshalIndent(data, "", " ") require.NoError(t, err) diff --git a/cmd/query/app/apiv3/http_gateway.go b/cmd/query/app/apiv3/http_gateway.go index fd98c09e140..9bb6535af9d 100644 --- a/cmd/query/app/apiv3/http_gateway.go +++ b/cmd/query/app/apiv3/http_gateway.go @@ -66,7 +66,7 @@ func (h *HTTPGateway) addRoute( router *mux.Router, f func(http.ResponseWriter, *http.Request), route string, - args ...interface{}, + args ...any, ) *mux.Route { var handler http.Handler = http.HandlerFunc(f) if h.TenancyMgr.Enabled { diff --git a/cmd/query/app/grpc_handler.go b/cmd/query/app/grpc_handler.go index fa8992f9f09..670050f5ba9 100644 --- a/cmd/query/app/grpc_handler.go +++ b/cmd/query/app/grpc_handler.go @@ -323,7 +323,7 @@ func (g *GRPCHandler) handleErr(msg string, err error) error { return status.Errorf(codes.Internal, "%s: %v", msg, err) } -func (g *GRPCHandler) newBaseQueryParameters(r interface{}) (bqp metricsstore.BaseQueryParameters, err error) { +func (g *GRPCHandler) newBaseQueryParameters(r any) (bqp metricsstore.BaseQueryParameters, err error) { if r == nil { return bqp, errNilRequest } diff --git a/cmd/query/app/grpc_handler_test.go b/cmd/query/app/grpc_handler_test.go index 2254bd2de12..697f6aeb8b0 100644 --- a/cmd/query/app/grpc_handler_test.go +++ b/cmd/query/app/grpc_handler_test.go @@ -1109,7 +1109,7 @@ func TestTenancyContextFlowGRPC(t *testing.T) { } addTenantedGetServices := func(mockReader *spanstoremocks.Reader, tenant string, expectedServices []string) { - mockReader.On("GetServices", mock.MatchedBy(func(v interface{}) bool { + mockReader.On("GetServices", mock.MatchedBy(func(v any) bool { ctx, ok := v.(context.Context) if !ok { return false @@ -1121,7 +1121,7 @@ func TestTenancyContextFlowGRPC(t *testing.T) { })).Return(expectedServices, nil).Once() } addTenantedGetTrace := func(mockReader *spanstoremocks.Reader, tenant string, trace *model.Trace, err error) { - mockReader.On("GetTrace", mock.MatchedBy(func(v interface{}) bool { + mockReader.On("GetTrace", mock.MatchedBy(func(v any) bool { ctx, ok := v.(context.Context) if !ok { return false diff --git a/cmd/query/app/handler_deps_test.go b/cmd/query/app/handler_deps_test.go index d68af45dae6..50394e4c429 100644 --- a/cmd/query/app/handler_deps_test.go +++ b/cmd/query/app/handler_deps_test.go @@ -318,8 +318,8 @@ func TestGetDependenciesSuccess(t *testing.T) { var response structuredResponse err := getJSON(ts.server.URL+"/api/dependencies?endTs=1476374248550&service=queen", &response) assert.NotEmpty(t, response.Data) - data := response.Data.([]interface{})[0] - actual := data.(map[string]interface{}) + data := response.Data.([]any)[0] + actual := data.(map[string]any) assert.Equal(t, "killer", actual["parent"]) assert.Equal(t, "queen", actual["child"]) assert.Equal(t, 12.00, actual["callCount"]) // recovered type is float diff --git a/cmd/query/app/http_handler.go b/cmd/query/app/http_handler.go index 09d647e90ed..a9dc13d7828 100644 --- a/cmd/query/app/http_handler.go +++ b/cmd/query/app/http_handler.go @@ -63,7 +63,7 @@ type HTTPHandler interface { } type structuredResponse struct { - Data interface{} `json:"data"` + Data any `json:"data"` Total int `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` @@ -141,7 +141,7 @@ func (aH *APIHandler) handleFunc( router *mux.Router, f func(http.ResponseWriter, *http.Request), routeFmt string, - args ...interface{}, + args ...any, ) *mux.Route { route := aH.formatRoute(routeFmt, args...) var handler http.Handler = http.HandlerFunc(f) @@ -155,8 +155,8 @@ func (aH *APIHandler) handleFunc( return router.HandleFunc(route, traceMiddleware.ServeHTTP) } -func (aH *APIHandler) formatRoute(route string, args ...interface{}) string { - args = append([]interface{}{aH.apiPrefix}, args...) +func (aH *APIHandler) formatRoute(route string, args ...any) string { + args = append([]any{aH.apiPrefix}, args...) return fmt.Sprintf("/%s"+route, args...) } @@ -516,7 +516,7 @@ func (aH *APIHandler) handleError(w http.ResponseWriter, err error, statusCode i return true } -func (aH *APIHandler) writeJSON(w http.ResponseWriter, r *http.Request, response interface{}) { +func (aH *APIHandler) writeJSON(w http.ResponseWriter, r *http.Request, response any) { prettyPrintValue := r.FormValue(prettyPrintParam) prettyPrint := prettyPrintValue != "" && prettyPrintValue != "false" diff --git a/cmd/query/app/http_handler_test.go b/cmd/query/app/http_handler_test.go index e74dd2ce23a..ef14c6b20a6 100644 --- a/cmd/query/app/http_handler_test.go +++ b/cmd/query/app/http_handler_test.go @@ -217,7 +217,7 @@ func (h *httpResponseErrWriter) Header() http.Header { func TestWriteJSON(t *testing.T) { testCases := []struct { name string - data interface{} + data any param string output string httpWriteErr bool @@ -530,7 +530,7 @@ func TestGetServicesSuccess(t *testing.T) { err := getJSON(ts.server.URL+"/api/services", &response) require.NoError(t, err) actualServices := make([]string, len(expectedServices)) - for i, s := range response.Data.([]interface{}) { + for i, s := range response.Data.([]any) { actualServices[i] = s.(string) } assert.Equal(t, expectedServices, actualServices) @@ -617,7 +617,7 @@ func TestGetOperationsLegacySuccess(t *testing.T) { err := getJSON(ts.server.URL+"/api/services/abc%2Ftrifle/operations", &response) require.NoError(t, err) - assert.ElementsMatch(t, expectedOperationNames, response.Data.([]interface{})) + assert.ElementsMatch(t, expectedOperationNames, response.Data.([]any)) } func TestGetOperationsLegacyStorageFailure(t *testing.T) { @@ -634,7 +634,7 @@ func TestGetOperationsLegacyStorageFailure(t *testing.T) { func TestTransformOTLPSuccess(t *testing.T) { reformat := func(in []byte) []byte { - obj := new(interface{}) + obj := new(any) require.NoError(t, json.Unmarshal(in, obj)) // format json similar to `jq .` out, err := json.MarshalIndent(obj, "", " ") @@ -671,7 +671,7 @@ func TestTransformOTLPReadError(t *testing.T) { func TestTransformOTLPBadPayload(t *testing.T) { withTestServer(func(ts *testServer) { - response := new(interface{}) + response := new(any) request := "Bad Payload" err := postJSON(ts.server.URL+"/api/transform", request, response) require.ErrorContains(t, err, "cannot unmarshal OTLP") @@ -777,7 +777,7 @@ func TestMetricsReaderError(t *testing.T) { urlPath string mockedQueryMethod string mockedQueryMethodParamType string - mockedResponse interface{} + mockedResponse any wantErrorMessage string }{ { @@ -842,7 +842,7 @@ func TestMetricsQueryDisabled(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { // Test - var response interface{} + var response any err := getJSON(ts.server.URL+tc.urlPath, &response) // Verify @@ -876,11 +876,11 @@ func TestGetMinStep(t *testing.T) { } // getJSON fetches a JSON document from a server via HTTP GET -func getJSON(url string, out interface{}) error { +func getJSON(url string, out any) error { return getJSONCustomHeaders(url, make(map[string]string), out) } -func getJSONCustomHeaders(url string, additionalHeaders map[string]string, out interface{}) error { +func getJSONCustomHeaders(url string, additionalHeaders map[string]string, out any) error { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return err @@ -889,7 +889,7 @@ func getJSONCustomHeaders(url string, additionalHeaders map[string]string, out i } // postJSON submits a JSON document to a server via HTTP POST and parses response as JSON. -func postJSON(url string, req interface{}, out interface{}) error { +func postJSON(url string, req any, out any) error { buf := &bytes.Buffer{} encoder := json.NewEncoder(buf) if err := encoder.Encode(req); err != nil { @@ -903,7 +903,7 @@ func postJSON(url string, req interface{}, out interface{}) error { } // execJSON executes an http request against a server and parses response as JSON -func execJSON(req *http.Request, additionalHeaders map[string]string, out interface{}) error { +func execJSON(req *http.Request, additionalHeaders map[string]string, out any) error { req.Header.Add("Accept", "application/json") for k, v := range additionalHeaders { req.Header.Add(k, v) @@ -1006,14 +1006,14 @@ func TestSearchTenancyFlowTenantHTTP(t *testing.T) { tenancy.NewManager(&tenancyOptions), querysvc.QueryServiceOptions{}) defer ts.server.Close() - ts.spanReader.On("GetTrace", mock.MatchedBy(func(v interface{}) bool { + ts.spanReader.On("GetTrace", mock.MatchedBy(func(v any) bool { ctx, ok := v.(context.Context) if !ok || tenancy.GetTenant(ctx) != "acme" { return false } return true }), mock.AnythingOfType("model.TraceID")).Return(mockTrace, nil).Twice() - ts.spanReader.On("GetTrace", mock.MatchedBy(func(v interface{}) bool { + ts.spanReader.On("GetTrace", mock.MatchedBy(func(v any) bool { ctx, ok := v.(context.Context) if !ok || tenancy.GetTenant(ctx) != "megacorp" { return false diff --git a/cmd/query/app/json_marshaler.go b/cmd/query/app/json_marshaler.go index 3601a141b8b..4a75de6c4d6 100644 --- a/cmd/query/app/json_marshaler.go +++ b/cmd/query/app/json_marshaler.go @@ -23,7 +23,7 @@ import ( "github.com/gogo/protobuf/proto" ) -type jsonMarshaler = func(writer io.Writer, response interface{}) error +type jsonMarshaler = func(writer io.Writer, response any) error // newProtoJSONMarshaler returns a protobuf-friendly JSON marshaler that knows how to handle protobuf-specific // field types such as "oneof" as well as dealing with NaNs which are not supported by JSON. @@ -32,7 +32,7 @@ func newProtoJSONMarshaler(prettyPrint bool) jsonMarshaler { if prettyPrint { marshaler.Indent = prettyPrintIndent } - return func(w io.Writer, response interface{}) error { + return func(w io.Writer, response any) error { return marshaler.Marshal(w, response.(proto.Message)) } } @@ -41,11 +41,11 @@ func newProtoJSONMarshaler(prettyPrint bool) jsonMarshaler { func newStructJSONMarshaler(prettyPrint bool) jsonMarshaler { marshaler := json.Marshal if prettyPrint { - marshaler = func(v interface{}) ([]byte, error) { + marshaler = func(v any) ([]byte, error) { return json.MarshalIndent(v, "", prettyPrintIndent) } } - return func(w io.Writer, response interface{}) error { + return func(w io.Writer, response any) error { resp, err := marshaler(response) if err != nil { return fmt.Errorf("failed marshalling HTTP response to JSON: %w", err) diff --git a/cmd/query/app/static_handler.go b/cmd/query/app/static_handler.go index 826c52bc962..ee27fe9dbe4 100644 --- a/cmd/query/app/static_handler.go +++ b/cmd/query/app/static_handler.go @@ -187,7 +187,7 @@ func loadUIConfig(uiConfig string) (*loadedConfig, error) { ext := filepath.Ext(uiConfig) switch strings.ToLower(ext) { case ".json": - var c map[string]interface{} + var c map[string]any if err := json.Unmarshal(bytesConfig, &c); err != nil { return nil, fmt.Errorf("cannot parse UI config file %v: %w", uiConfig, err) diff --git a/cmd/query/app/static_handler_test.go b/cmd/query/app/static_handler_test.go index 461f7a44f3b..5f2cda04c87 100644 --- a/cmd/query/app/static_handler_test.go +++ b/cmd/query/app/static_handler_test.go @@ -258,9 +258,9 @@ func TestLoadUIConfig(t *testing.T) { regexp: configPattern, }, }) - c, _ := json.Marshal(map[string]interface{}{ - "menu": []interface{}{ - map[string]interface{}{ + c, _ := json.Marshal(map[string]any{ + "menu": []any{ + map[string]any{ "label": "GitHub", "url": "https://github.com/jaegertracing/jaeger", }, diff --git a/examples/hotrod/pkg/log/spanlogger.go b/examples/hotrod/pkg/log/spanlogger.go index d8f64762943..582e22b1d91 100644 --- a/examples/hotrod/pkg/log/spanlogger.go +++ b/examples/hotrod/pkg/log/spanlogger.go @@ -172,5 +172,5 @@ func (e *bridgeFieldEncoder) AddUintptr(key string, value uintptr) { e.pairs = append(e.pairs, attribute.String(key, fmt.Sprint(value))) } -func (e *bridgeFieldEncoder) AddReflected(key string, value interface{}) error { return nil } -func (e *bridgeFieldEncoder) OpenNamespace(key string) {} +func (e *bridgeFieldEncoder) AddReflected(key string, value any) error { return nil } +func (e *bridgeFieldEncoder) OpenNamespace(key string) {} diff --git a/examples/hotrod/pkg/tracing/http.go b/examples/hotrod/pkg/tracing/http.go index dbea5c95ec8..bab10ec75f8 100644 --- a/examples/hotrod/pkg/tracing/http.go +++ b/examples/hotrod/pkg/tracing/http.go @@ -46,7 +46,7 @@ func NewHTTPClient(tp trace.TracerProvider) *HTTPClient { // GetJSON executes HTTP GET against specified url and tried to parse // the response into out object. -func (c *HTTPClient) GetJSON(ctx context.Context, endpoint string, url string, out interface{}) error { +func (c *HTTPClient) GetJSON(ctx context.Context, endpoint string, url string, out any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err diff --git a/examples/hotrod/services/frontend/server.go b/examples/hotrod/services/frontend/server.go index 7b451d977d5..65bf9bd5f99 100644 --- a/examples/hotrod/services/frontend/server.go +++ b/examples/hotrod/services/frontend/server.go @@ -131,7 +131,7 @@ func (s *Server) dispatch(w http.ResponseWriter, r *http.Request) { s.writeResponse(response, w, r) } -func (s *Server) writeResponse(response interface{}, w http.ResponseWriter, r *http.Request) { +func (s *Server) writeResponse(response any, w http.ResponseWriter, r *http.Request) { data, err := json.Marshal(response) if httperr.HandleError(w, err, http.StatusInternalServerError) { s.logger.For(r.Context()).Error("cannot marshal response", zap.Error(err)) diff --git a/internal/metricstest/local_test.go b/internal/metricstest/local_test.go index a99721dcc92..1383ffca17f 100644 --- a/internal/metricstest/local_test.go +++ b/internal/metricstest/local_test.go @@ -155,7 +155,7 @@ func TestLocalMetricsInterval(t *testing.T) { assert.NotNil(t, timer) // timer.hist.Current is modified on every Rotate(), which is called by Backend after every refreshInterval - getCurr := func() interface{} { + getCurr := func() any { timer.Lock() defer timer.Unlock() return timer.hist.Current diff --git a/model/converter/json/from_domain.go b/model/converter/json/from_domain.go index 26c2e47d6f0..b5d484741bc 100644 --- a/model/converter/json/from_domain.go +++ b/model/converter/json/from_domain.go @@ -120,7 +120,7 @@ func (fd fromDomain) convertRefType(refType model.SpanRefType) json.ReferenceTyp func (fd fromDomain) convertKeyValues(keyValues model.KeyValues) []json.KeyValue { out := make([]json.KeyValue, len(keyValues)) for i, kv := range keyValues { - var value interface{} + var value any switch kv.VType { case model.StringType: value = kv.VStr diff --git a/model/converter/json/from_domain_test.go b/model/converter/json/from_domain_test.go index 3bdb7968ce5..7d507caf894 100644 --- a/model/converter/json/from_domain_test.go +++ b/model/converter/json/from_domain_test.go @@ -125,7 +125,7 @@ func loadFixtures(t *testing.T, i int, processEmbedded bool) ([]byte, []byte) { return inStr, outStr } -func testJSONEncoding(t *testing.T, i int, expectedStr []byte, object interface{}, processEmbedded bool) { +func testJSONEncoding(t *testing.T, i int, expectedStr []byte, object any, processEmbedded bool) { buf := &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetIndent("", " ") diff --git a/model/converter/thrift/jaeger/to_domain_test.go b/model/converter/thrift/jaeger/to_domain_test.go index 00cf9b206c6..8d43bdf8c61 100644 --- a/model/converter/thrift/jaeger/to_domain_test.go +++ b/model/converter/thrift/jaeger/to_domain_test.go @@ -88,7 +88,7 @@ func loadBatch(t *testing.T, file string) *jaeger.Batch { return &batch } -func loadJSON(t *testing.T, fileName string, obj interface{}) { +func loadJSON(t *testing.T, fileName string, obj any) { jsonFile, err := os.Open(fileName) require.NoError(t, err, "Failed to load json fixture file %s", fileName) jsonParser := json.NewDecoder(jsonFile) diff --git a/model/converter/thrift/zipkin/to_domain.go b/model/converter/thrift/zipkin/to_domain.go index f4dd3655f74..d0cc39d87cb 100644 --- a/model/converter/thrift/zipkin/to_domain.go +++ b/model/converter/thrift/zipkin/to_domain.go @@ -346,7 +346,7 @@ func (td toDomain) transformBinaryAnnotation(binaryAnnotation *zipkincore.Binary return model.KeyValue{}, fmt.Errorf("unknown zipkin annotation type: %d", binaryAnnotation.AnnotationType) } -func bytesToNumber(b []byte, number interface{}) error { +func bytesToNumber(b []byte, number any) error { buf := bytes.NewReader(b) return binary.Read(buf, binary.BigEndian, number) } diff --git a/model/converter/thrift/zipkin/to_domain_test.go b/model/converter/thrift/zipkin/to_domain_test.go index 63dc9de6a92..986f33598b9 100644 --- a/model/converter/thrift/zipkin/to_domain_test.go +++ b/model/converter/thrift/zipkin/to_domain_test.go @@ -171,7 +171,7 @@ func TestInvalidAnnotationTypeError(t *testing.T) { // TestZipkinEncoding is just for reference to explain the base64 strings // used in zipkin_03.json and jaeger_03.json fixtures func TestValidateBase64Values(t *testing.T) { - numberToBase64 := func(num interface{}) string { + numberToBase64 := func(num any) string { buf := &bytes.Buffer{} binary.Write(buf, binary.BigEndian, num) encoded := base64.StdEncoding.EncodeToString(buf.Bytes()) @@ -209,7 +209,7 @@ func getZipkinSpans(t *testing.T, s string) []*z.Span { return zSpans } -func loadJSON(t *testing.T, fileName string, i interface{}) { +func loadJSON(t *testing.T, fileName string, i any) { jsonFile, err := os.Open(fileName) require.NoError(t, err, "Failed to load json fixture file %s", fileName) jsonParser := json.NewDecoder(jsonFile) diff --git a/model/json/model.go b/model/json/model.go index 8d72dc498e5..ba1b5a44aba 100644 --- a/model/json/model.go +++ b/model/json/model.go @@ -98,9 +98,9 @@ type Log struct { // KeyValue is a key-value pair with typed value. type KeyValue struct { - Key string `json:"key"` - Type ValueType `json:"type,omitempty"` - Value interface{} `json:"value"` + Key string `json:"key"` + Type ValueType `json:"type,omitempty"` + Value any `json:"value"` } // DependencyLink shows dependencies between services diff --git a/model/keyvalue.go b/model/keyvalue.go index 44f3e1bdb03..96c15dfaa81 100644 --- a/model/keyvalue.go +++ b/model/keyvalue.go @@ -102,8 +102,8 @@ func (kv *KeyValue) Binary() []byte { return nil } -// Value returns typed values stored in KeyValue as interface{}. -func (kv *KeyValue) Value() interface{} { +// Value returns typed values stored in KeyValue as any. +func (kv *KeyValue) Value() any { switch kv.VType { case StringType: return kv.VStr diff --git a/model/keyvalue_test.go b/model/keyvalue_test.go index 054704e3814..87dfb72a036 100644 --- a/model/keyvalue_test.go +++ b/model/keyvalue_test.go @@ -120,7 +120,7 @@ func TestKeyValueAsStringAndValue(t *testing.T) { kv model.KeyValue str string strLossy string - val interface{} + val any }{ {name: "Bender is great!", kv: model.String("x", "Bender is great!"), str: "Bender is great!", val: "Bender is great!"}, {name: "false", kv: model.Bool("x", false), str: "false", val: false}, diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 5bd79b54b5e..14a4c0bb6be 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -24,10 +24,10 @@ import ( type Cache interface { // Get retrieves an element based on a key, returning nil if the element // does not exist - Get(key string) interface{} + Get(key string) any // Put adds an element to the cache, returning the previous element - Put(key string, value interface{}) interface{} + Put(key string, value any) any // Delete deletes an element in the cache Delete(key string) @@ -37,7 +37,7 @@ type Cache interface { // CompareAndSwap adds an element to the cache if the existing entry matches the old value. // It returns the element in cache after function is executed and true if the element was replaced, false otherwise. - CompareAndSwap(key string, old, new interface{}) (interface{}, bool) + CompareAndSwap(key string, old, new any) (any, bool) } // Options control the behavior of the cache @@ -58,4 +58,4 @@ type Options struct { // EvictCallback is a type for notifying applications when an item is // scheduled for eviction from the Cache. -type EvictCallback func(key string, value interface{}) +type EvictCallback func(key string, value any) diff --git a/pkg/cache/lru.go b/pkg/cache/lru.go index 2881ec822b6..0ffd0e63218 100644 --- a/pkg/cache/lru.go +++ b/pkg/cache/lru.go @@ -56,7 +56,7 @@ func NewLRUWithOptions(maxSize int, opts *Options) *LRU { } // Get retrieves the value stored under the given key -func (c *LRU) Get(key string) interface{} { +func (c *LRU) Get(key string) any { c.mux.Lock() defer c.mux.Unlock() @@ -81,7 +81,7 @@ func (c *LRU) Get(key string) interface{} { } // Put puts a new value associated with a given key, returning the existing value (if present) -func (c *LRU) Put(key string, value interface{}) interface{} { +func (c *LRU) Put(key string, value any) any { c.mux.Lock() defer c.mux.Unlock() elt := c.byKey[key] @@ -90,7 +90,7 @@ func (c *LRU) Put(key string, value interface{}) interface{} { // CompareAndSwap puts a new value associated with a given key if existing value matches oldValue. // It returns itemInCache as the element in cache after the function is executed and replaced as true if value is replaced, false otherwise. -func (c *LRU) CompareAndSwap(key string, oldValue, newValue interface{}) (itemInCache interface{}, replaced bool) { +func (c *LRU) CompareAndSwap(key string, oldValue, newValue any) (itemInCache any, replaced bool) { c.mux.Lock() defer c.mux.Unlock() @@ -113,7 +113,7 @@ func (c *LRU) CompareAndSwap(key string, oldValue, newValue interface{}) (itemIn // putWithMutexHold populates the cache and returns the inserted value. // Caller is expected to hold the c.mut mutex before calling. -func (c *LRU) putWithMutexHold(key string, value interface{}, elt *list.Element) interface{} { +func (c *LRU) putWithMutexHold(key string, value any, elt *list.Element) any { if elt != nil { entry := elt.Value.(*cacheEntry) existing := entry.value @@ -171,5 +171,5 @@ func (c *LRU) Size() int { type cacheEntry struct { key string expiration time.Time - value interface{} + value any } diff --git a/pkg/cache/lru_test.go b/pkg/cache/lru_test.go index 52eeed09413..2e8d462ef35 100644 --- a/pkg/cache/lru_test.go +++ b/pkg/cache/lru_test.go @@ -27,7 +27,7 @@ import ( func TestLRU(t *testing.T) { cache := NewLRUWithOptions(4, &Options{ - OnEvict: func(k string, i interface{}) { + OnEvict: func(k string, i any) { // do nothing, just for code coverage }, }) @@ -176,7 +176,7 @@ func TestLRUCacheConcurrentAccess(t *testing.T) { func TestRemoveFunc(t *testing.T) { ch := make(chan bool) cache := NewLRUWithOptions(5, &Options{ - OnEvict: func(k string, i interface{}) { + OnEvict: func(k string, i any) { go func() { _, ok := i.(*testing.T) assert.True(t, ok) @@ -202,7 +202,7 @@ func TestRemovedFuncWithTTL(t *testing.T) { ch := make(chan bool) cache := NewLRUWithOptions(5, &Options{ TTL: time.Millisecond * 5, - OnEvict: func(k string, i interface{}) { + OnEvict: func(k string, i any) { go func() { _, ok := i.(*testing.T) assert.True(t, ok) diff --git a/pkg/cassandra/gocql/gocql.go b/pkg/cassandra/gocql/gocql.go index 4d96eaebd2d..063284f04f1 100644 --- a/pkg/cassandra/gocql/gocql.go +++ b/pkg/cassandra/gocql/gocql.go @@ -32,7 +32,7 @@ func WrapCQLSession(session *gocql.Session) CQLSession { } // Query delegates to gocql.Session#Query and wraps the result as Query. -func (s CQLSession) Query(stmt string, values ...interface{}) cassandra.Query { +func (s CQLSession) Query(stmt string, values ...any) cassandra.Query { return WrapCQLQuery(s.session.Query(stmt, values...)) } @@ -59,7 +59,7 @@ func (q CQLQuery) Exec() error { } // ScanCAS delegates to gocql.Query#ScanCAS. -func (q CQLQuery) ScanCAS(dest ...interface{}) (bool, error) { +func (q CQLQuery) ScanCAS(dest ...any) (bool, error) { return q.query.ScanCAS(dest...) } @@ -69,7 +69,7 @@ func (q CQLQuery) Iter() cassandra.Iterator { } // Bind delegates to gocql.Query#Bind and wraps the result as Query. -func (q CQLQuery) Bind(v ...interface{}) cassandra.Query { +func (q CQLQuery) Bind(v ...any) cassandra.Query { return WrapCQLQuery(q.query.Bind(v...)) } @@ -101,7 +101,7 @@ func WrapCQLIterator(iter *gocql.Iter) CQLIterator { } // Scan delegates to gocql.Iter#Scan. -func (i CQLIterator) Scan(dest ...interface{}) bool { +func (i CQLIterator) Scan(dest ...any) bool { return i.iter.Scan(dest...) } diff --git a/pkg/cassandra/metrics/table_test.go b/pkg/cassandra/metrics/table_test.go index e4daf427995..241aa4dcdfb 100644 --- a/pkg/cassandra/metrics/table_test.go +++ b/pkg/cassandra/metrics/table_test.go @@ -155,7 +155,7 @@ func (q insertQuery) String() string { return q.str } -func (q insertQuery) ScanCAS(dest ...interface{}) (bool, error) { +func (q insertQuery) ScanCAS(dest ...any) (bool, error) { return true, nil } diff --git a/pkg/cassandra/session.go b/pkg/cassandra/session.go index b468584330d..e8f9cd13a2a 100644 --- a/pkg/cassandra/session.go +++ b/pkg/cassandra/session.go @@ -41,7 +41,7 @@ const ( // Session is an abstraction of gocql.Session type Session interface { - Query(stmt string, values ...interface{}) Query + Query(stmt string, values ...any) Query Close() } @@ -54,20 +54,20 @@ type UpdateQuery interface { // statement containing an IF clause). If the transaction fails because // the existing values did not match, the previous values will be stored // in dest. - ScanCAS(dest ...interface{}) (bool, error) + ScanCAS(dest ...any) (bool, error) } // Query is an abstraction of gocql.Query type Query interface { UpdateQuery Iter() Iterator - Bind(v ...interface{}) Query + Bind(v ...any) Query Consistency(level Consistency) Query PageSize(int) Query } // Iterator is an abstraction of gocql.Iter type Iterator interface { - Scan(dest ...interface{}) bool + Scan(dest ...any) bool Close() error } diff --git a/pkg/es/client.go b/pkg/es/client.go index 8369b7fcdae..14b9ac77434 100644 --- a/pkg/es/client.go +++ b/pkg/es/client.go @@ -62,7 +62,7 @@ type IndexService interface { Index(index string) IndexService Type(typ string) IndexService Id(id string) IndexService - BodyJson(body interface{}) IndexService + BodyJson(body any) IndexService Add() } diff --git a/pkg/es/client/cluster_client.go b/pkg/es/client/cluster_client.go index 0f90acab421..2a074ab0875 100644 --- a/pkg/es/client/cluster_client.go +++ b/pkg/es/client/cluster_client.go @@ -32,8 +32,8 @@ type ClusterClient struct { // Version returns the major version of the ES cluster func (c *ClusterClient) Version() (uint, error) { type clusterInfo struct { - Version map[string]interface{} `json:"version"` - TagLine string `json:"tagline"` + Version map[string]any `json:"version"` + TagLine string `json:"tagline"` } body, err := c.request(elasticRequest{ endpoint: "", diff --git a/pkg/es/client/index_client.go b/pkg/es/client/index_client.go index 1c516b99ef1..f55c13070c2 100644 --- a/pkg/es/client/index_client.go +++ b/pkg/es/client/index_client.go @@ -76,8 +76,8 @@ func (i *IndicesClient) GetJaegerIndices(prefix string) ([]Index, error) { } type indexInfo struct { - Aliases map[string]interface{} `json:"aliases"` - Settings map[string]string `json:"settings"` + Aliases map[string]any `json:"aliases"` + Settings map[string]string `json:"settings"` } var indicesInfo map[string]indexInfo if err = json.Unmarshal(body, &indicesInfo); err != nil { @@ -204,22 +204,22 @@ func (i *IndicesClient) aliasesString(aliases []Alias) string { } func (i *IndicesClient) aliasAction(action string, aliases []Alias) error { - actions := []map[string]interface{}{} + actions := []map[string]any{} for _, alias := range aliases { - options := map[string]interface{}{ + options := map[string]any{ "index": alias.Index, "alias": alias.Name, } if alias.IsWriteIndex { options["is_write_index"] = true } - actions = append(actions, map[string]interface{}{ + actions = append(actions, map[string]any{ action: options, }) } - body := map[string]interface{}{ + body := map[string]any{ "actions": actions, } @@ -269,13 +269,13 @@ func (i IndicesClient) CreateTemplate(template, name string) error { } // Rollover create a rollover for certain index/alias -func (i IndicesClient) Rollover(rolloverTarget string, conditions map[string]interface{}) error { +func (i IndicesClient) Rollover(rolloverTarget string, conditions map[string]any) error { esReq := elasticRequest{ endpoint: fmt.Sprintf("%s/_rollover/", rolloverTarget), method: http.MethodPost, } if len(conditions) > 0 { - body := map[string]interface{}{ + body := map[string]any{ "conditions": conditions, } bodyBytes, err := json.Marshal(body) diff --git a/pkg/es/client/index_client_test.go b/pkg/es/client/index_client_test.go index 94be6f7df58..57610fdd5d1 100644 --- a/pkg/es/client/index_client_test.go +++ b/pkg/es/client/index_client_test.go @@ -545,7 +545,7 @@ func TestClientCreateTemplate(t *testing.T) { func TestRollover(t *testing.T) { expectedRequestBody := "{\"conditions\":{\"max_age\":\"2d\"}}" - mapConditions := map[string]interface{}{ + mapConditions := map[string]any{ "max_age": "2d", } diff --git a/pkg/es/client/interfaces.go b/pkg/es/client/interfaces.go index 9ea6fcff31f..85ceba15855 100644 --- a/pkg/es/client/interfaces.go +++ b/pkg/es/client/interfaces.go @@ -21,7 +21,7 @@ type IndexAPI interface { CreateAlias(aliases []Alias) error DeleteAlias(aliases []Alias) error CreateTemplate(template, name string) error - Rollover(rolloverTarget string, conditions map[string]interface{}) error + Rollover(rolloverTarget string, conditions map[string]any) error } type ClusterAPI interface { diff --git a/pkg/es/textTemplate.go b/pkg/es/textTemplate.go index 9d89d05712c..f932731d9a8 100644 --- a/pkg/es/textTemplate.go +++ b/pkg/es/textTemplate.go @@ -21,7 +21,7 @@ import ( // TemplateApplier applies a parsed template to input data that maps to the template's variables. type TemplateApplier interface { - Execute(wr io.Writer, data interface{}) error + Execute(wr io.Writer, data any) error } // TemplateBuilder parses a given string and returns TemplateApplier diff --git a/pkg/es/wrapper/wrapper_nolint.go b/pkg/es/wrapper/wrapper_nolint.go index c28830e1dfb..3f076e252c7 100644 --- a/pkg/es/wrapper/wrapper_nolint.go +++ b/pkg/es/wrapper/wrapper_nolint.go @@ -25,6 +25,6 @@ func (i IndexServiceWrapper) Id(id string) es.IndexService { } // BodyJson calls this function to internal service. -func (i IndexServiceWrapper) BodyJson(body interface{}) es.IndexService { +func (i IndexServiceWrapper) BodyJson(body any) es.IndexService { return WrapESIndexService(i.bulkIndexReq.Doc(body), i.bulkService, i.esVersion) } diff --git a/pkg/fswatcher/fswatcher_test.go b/pkg/fswatcher/fswatcher_test.go index 68a431e9e02..12fd552cea3 100644 --- a/pkg/fswatcher/fswatcher_test.go +++ b/pkg/fswatcher/fswatcher_test.go @@ -225,7 +225,7 @@ func createTimestampDir(t *testing.T, dir string) { } type delayedFormat struct { - fn func() interface{} + fn func() any } func (df delayedFormat) String() string { @@ -237,7 +237,7 @@ func assertLogs(t *testing.T, f func() bool, errorMsg string, logObserver *obser 10*time.Second, 10*time.Millisecond, errorMsg, delayedFormat{ - fn: func() interface{} { return logObserver.All() }, + fn: func() any { return logObserver.All() }, }, ) } diff --git a/pkg/gogocodec/codec.go b/pkg/gogocodec/codec.go index f7df1c2d2ec..946db0e3ad4 100644 --- a/pkg/gogocodec/codec.go +++ b/pkg/gogocodec/codec.go @@ -66,7 +66,7 @@ func (c *gogoCodec) Name() string { } // Marshal implements encoding.Codec -func (c *gogoCodec) Marshal(v interface{}) ([]byte, error) { +func (c *gogoCodec) Marshal(v any) ([]byte, error) { t := reflect.TypeOf(v) elem := t.Elem() // use gogo proto only for Jaeger types @@ -77,7 +77,7 @@ func (c *gogoCodec) Marshal(v interface{}) ([]byte, error) { } // Unmarshal implements encoding.Codec -func (c *gogoCodec) Unmarshal(data []byte, v interface{}) error { +func (c *gogoCodec) Unmarshal(data []byte, v any) error { t := reflect.TypeOf(v) elem := t.Elem() // only for collections // use gogo proto only for Jaeger types diff --git a/pkg/gzipfs/gzip.go b/pkg/gzipfs/gzip.go index cc58883f94a..2f478427548 100644 --- a/pkg/gzipfs/gzip.go +++ b/pkg/gzipfs/gzip.go @@ -80,7 +80,7 @@ func (fi fileInfo) ModTime() time.Time { return fi.info.ModTime() } func (fi fileInfo) IsDir() bool { return fi.info.IsDir() } -func (fi fileInfo) Sys() interface{} { return nil } +func (fi fileInfo) Sys() any { return nil } // New wraps underlying fs that is expected to contain gzipped files // and presents an unzipped view of it. diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 86cf913bc94..a7954ded67d 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -32,7 +32,7 @@ import ( // of type Counter or Gauge or Timer. // // Errors during Init lead to a panic. -func MustInit(metrics interface{}, factory Factory, globalTags map[string]string) { +func MustInit(metrics any, factory Factory, globalTags map[string]string) { if err := Init(metrics, factory, globalTags); err != nil { panic(err.Error()) } @@ -40,7 +40,7 @@ func MustInit(metrics interface{}, factory Factory, globalTags map[string]string // Init does the same as MustInit, but returns an error instead of // panicking. -func Init(m interface{}, factory Factory, globalTags map[string]string) error { +func Init(m any, factory Factory, globalTags map[string]string) error { // Allow user to opt out of reporting metrics by passing in nil. if factory == nil { factory = NullFactory @@ -101,7 +101,7 @@ func Init(m interface{}, factory Factory, globalTags map[string]string) error { } } help := field.Tag.Get("help") - var obj interface{} + var obj any switch { case field.Type.AssignableTo(counterPtrType): obj = factory.Counter(Options{ diff --git a/pkg/queue/bounded_queue.go b/pkg/queue/bounded_queue.go index c28031104e6..a0ef1f0abae 100644 --- a/pkg/queue/bounded_queue.go +++ b/pkg/queue/bounded_queue.go @@ -26,7 +26,7 @@ import ( // Consumer consumes data from a bounded queue type Consumer interface { - Consume(item interface{}) + Consume(item any) } // BoundedQueue implements a producer-consumer exchange similar to a ring buffer queue, @@ -40,16 +40,16 @@ type BoundedQueue struct { size atomic.Int32 capacity atomic.Uint32 stopped atomic.Uint32 - items *chan interface{} - onDroppedItem func(item interface{}) + items *chan any + onDroppedItem func(item any) factory func() Consumer stopCh chan struct{} } // NewBoundedQueue constructs the new queue of specified capacity, and with an optional // callback for dropped items (e.g. useful to emit metrics). -func NewBoundedQueue(capacity int, onDroppedItem func(item interface{})) *BoundedQueue { - queue := make(chan interface{}, capacity) +func NewBoundedQueue(capacity int, onDroppedItem func(item any)) *BoundedQueue { + queue := make(chan any, capacity) bq := &BoundedQueue{ onDroppedItem: onDroppedItem, items: &queue, @@ -95,23 +95,23 @@ func (q *BoundedQueue) StartConsumersWithFactory(num int, factory func() Consume // ConsumerFunc is an adapter to allow the use of // a consume function callback as a Consumer. -type ConsumerFunc func(item interface{}) +type ConsumerFunc func(item any) // Consume calls c(item) -func (c ConsumerFunc) Consume(item interface{}) { +func (c ConsumerFunc) Consume(item any) { c(item) } // StartConsumers starts a given number of goroutines consuming items from the queue // and passing them into the consumer callback. -func (q *BoundedQueue) StartConsumers(num int, callback func(item interface{})) { +func (q *BoundedQueue) StartConsumers(num int, callback func(item any)) { q.StartConsumersWithFactory(num, func() Consumer { return ConsumerFunc(callback) }) } // Produce is used by the producer to submit new item to the queue. Returns false in case of queue overflow. -func (q *BoundedQueue) Produce(item interface{}) bool { +func (q *BoundedQueue) Produce(item any) bool { if q.stopped.Load() != 0 { q.onDroppedItem(item) return false @@ -185,7 +185,7 @@ func (q *BoundedQueue) Resize(capacity int) bool { } previous := *q.items - queue := make(chan interface{}, capacity) + queue := make(chan any, capacity) // swap queues // #nosec diff --git a/pkg/queue/bounded_queue_test.go b/pkg/queue/bounded_queue_test.go index 270adc03252..36c508b2872 100644 --- a/pkg/queue/bounded_queue_test.go +++ b/pkg/queue/bounded_queue_test.go @@ -34,12 +34,12 @@ import ( // In this test we run a queue with capacity 1 and a single consumer. // We want to test the overflow behavior, so we block the consumer // by holding a startLock before submitting items to the queue. -func helper(t *testing.T, startConsumers func(q *BoundedQueue, consumerFn func(item interface{}))) { +func helper(t *testing.T, startConsumers func(q *BoundedQueue, consumerFn func(item any))) { mFact := metricstest.NewFactory(0) counter := mFact.Counter(metrics.Options{Name: "dropped", Tags: nil}) gauge := mFact.Gauge(metrics.Options{Name: "size", Tags: nil}) - q := NewBoundedQueue(1, func(item interface{}) { + q := NewBoundedQueue(1, func(item any) { counter.Inc(1) }) assert.Equal(t, 1, q.Capacity()) @@ -49,7 +49,7 @@ func helper(t *testing.T, startConsumers func(q *BoundedQueue, consumerFn func(i startLock.Lock() // block consumers consumerState := newConsumerState(t) - startConsumers(q, func(item interface{}) { + startConsumers(q, func(item any) { consumerState.record(item.(string)) // block further processing until startLock is released @@ -114,13 +114,13 @@ func helper(t *testing.T, startConsumers func(q *BoundedQueue, consumerFn func(i } func TestBoundedQueue(t *testing.T) { - helper(t, func(q *BoundedQueue, consumerFn func(item interface{})) { + helper(t, func(q *BoundedQueue, consumerFn func(item any)) { q.StartConsumers(1, consumerFn) }) } func TestBoundedQueueWithFactory(t *testing.T) { - helper(t, func(q *BoundedQueue, consumerFn func(item interface{})) { + helper(t, func(q *BoundedQueue, consumerFn func(item any)) { q.StartConsumersWithFactory(1, func() Consumer { return ConsumerFunc(consumerFn) }) }) } @@ -175,7 +175,7 @@ func (s *consumerState) assertConsumed(expected map[string]bool) { } func TestResizeUp(t *testing.T) { - q := NewBoundedQueue(2, func(item interface{}) { + q := NewBoundedQueue(2, func(item any) { fmt.Printf("dropped: %v\n", item) }) @@ -185,7 +185,7 @@ func TestResizeUp(t *testing.T) { releaseConsumers.Add(1) released, resized := false, false - q.StartConsumers(1, func(item interface{}) { + q.StartConsumers(1, func(item any) { if !resized { // we'll have a second consumer once the queue is resized // signal that the worker is processing firstConsumer.Done() @@ -226,7 +226,7 @@ func TestResizeUp(t *testing.T) { } func TestResizeDown(t *testing.T) { - q := NewBoundedQueue(4, func(item interface{}) { + q := NewBoundedQueue(4, func(item any) { fmt.Printf("dropped: %v\n", item) }) @@ -235,7 +235,7 @@ func TestResizeDown(t *testing.T) { releaseConsumers.Add(1) released := false - q.StartConsumers(1, func(item interface{}) { + q.StartConsumers(1, func(item any) { // once we release the lock, we might end up with multiple calls to reach this if !released { // signal that the worker is processing @@ -270,7 +270,7 @@ func TestResizeDown(t *testing.T) { } func TestResizeOldQueueIsDrained(t *testing.T) { - q := NewBoundedQueue(2, func(item interface{}) { + q := NewBoundedQueue(2, func(item any) { fmt.Printf("dropped: %v\n", item) }) @@ -283,7 +283,7 @@ func TestResizeOldQueueIsDrained(t *testing.T) { consumed.Store(5) first := true - q.StartConsumers(1, func(item interface{}) { + q.StartConsumers(1, func(item any) { // first run only if first { first = false @@ -319,23 +319,23 @@ func TestResizeOldQueueIsDrained(t *testing.T) { } func TestNoopResize(t *testing.T) { - q := NewBoundedQueue(2, func(item interface{}) {}) + q := NewBoundedQueue(2, func(item any) {}) assert.False(t, q.Resize(2)) } func TestZeroSize(t *testing.T) { - q := NewBoundedQueue(0, func(item interface{}) {}) + q := NewBoundedQueue(0, func(item any) {}) - q.StartConsumers(1, func(item interface{}) {}) + q.StartConsumers(1, func(item any) {}) defer q.Stop() assert.False(t, q.Produce("a")) // in process } func BenchmarkBoundedQueue(b *testing.B) { - q := NewBoundedQueue(1000, func(item interface{}) {}) - q.StartConsumers(10, func(item interface{}) {}) + q := NewBoundedQueue(1000, func(item any) {}) + q.StartConsumers(10, func(item any) {}) defer q.Stop() for n := 0; n < b.N; n++ { @@ -344,10 +344,10 @@ func BenchmarkBoundedQueue(b *testing.B) { } func BenchmarkBoundedQueueWithFactory(b *testing.B) { - q := NewBoundedQueue(1000, func(item interface{}) {}) + q := NewBoundedQueue(1000, func(item any) {}) q.StartConsumersWithFactory(10, func() Consumer { - return ConsumerFunc(func(item interface{}) {}) + return ConsumerFunc(func(item any) {}) }) defer q.Stop() diff --git a/pkg/recoveryhandler/zap.go b/pkg/recoveryhandler/zap.go index 678c179dade..4303248dae1 100644 --- a/pkg/recoveryhandler/zap.go +++ b/pkg/recoveryhandler/zap.go @@ -29,7 +29,7 @@ type zapRecoveryWrapper struct { } // Println logs an error message with the given fields -func (z zapRecoveryWrapper) Println(args ...interface{}) { +func (z zapRecoveryWrapper) Println(args ...any) { z.logger.Error(fmt.Sprint(args...)) } diff --git a/pkg/tenancy/grpc.go b/pkg/tenancy/grpc.go index 80d069d3825..d17cfada1e0 100644 --- a/pkg/tenancy/grpc.go +++ b/pkg/tenancy/grpc.go @@ -68,7 +68,7 @@ func directlyAttachedTenant(ctx context.Context) bool { // NewGuardingStreamInterceptor blocks handling of streams whose tenancy header doesn't meet tenancy requirements. // It also ensures the tenant is directly in the context, rather than context metadata. func NewGuardingStreamInterceptor(tc *Manager) grpc.StreamServerInterceptor { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { tenant, err := getValidTenant(ss.Context(), tc) if err != nil { return err @@ -100,7 +100,7 @@ func tenantFromMetadata(md metadata.MD, tenancyHeader string) (string, error) { // NewGuardingUnaryInterceptor blocks handling of RPCs whose tenancy header doesn't meet tenancy requirements. // It also ensures the tenant is directly in the context, rather than context metadata. func NewGuardingUnaryInterceptor(tc *Manager) grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { tenant, err := getValidTenant(ctx, tc) if err != nil { return nil, err @@ -119,7 +119,7 @@ func NewClientUnaryInterceptor(tc *Manager) grpc.UnaryClientInterceptor { return grpc.UnaryClientInterceptor(func( ctx context.Context, method string, - req, reply interface{}, + req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, diff --git a/pkg/tenancy/grpc_test.go b/pkg/tenancy/grpc_test.go index 1411e72c67a..f4b8777f217 100644 --- a/pkg/tenancy/grpc_test.go +++ b/pkg/tenancy/grpc_test.go @@ -83,7 +83,7 @@ func TestTenancyInterceptors(t *testing.T) { context: test.ctx, } ssi := grpc.StreamServerInfo{} - handler := func(interface{}, grpc.ServerStream) error { + handler := func(any, grpc.ServerStream) error { // do nothing return nil } @@ -98,7 +98,7 @@ func TestTenancyInterceptors(t *testing.T) { uinterceptor := NewGuardingUnaryInterceptor(test.tenancyMgr) usi := &grpc.UnaryServerInfo{} iface := 0 - uhandler := func(ctx context.Context, req interface{}) (interface{}, error) { + uhandler := func(ctx context.Context, req any) (any, error) { // do nothing return req, nil } @@ -118,7 +118,7 @@ func TestClientUnaryInterceptor(t *testing.T) { interceptor := NewClientUnaryInterceptor(tm) var tenant string fakeErr := errors.New("foo") - invoker := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { + invoker := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, opts ...grpc.CallOption) error { md, ok := metadata.FromOutgoingContext(ctx) assert.True(t, ok) ten, err := tenantFromMetadata(md, tm.Header) diff --git a/plugin/pkg/distributedlock/cassandra/lock_test.go b/plugin/pkg/distributedlock/cassandra/lock_test.go index f542abdfc04..65a33d580e7 100644 --- a/plugin/pkg/distributedlock/cassandra/lock_test.go +++ b/plugin/pkg/distributedlock/cassandra/lock_test.go @@ -81,8 +81,8 @@ func TestExtendLease(t *testing.T) { query := &mocks.Query{} query.On("ScanCAS", matchEverything()).Return(testCase.applied, testCase.errScan) - var args []interface{} - captureArgs := mock.MatchedBy(func(v []interface{}) bool { + var args []any + captureArgs := mock.MatchedBy(func(v []any) bool { args = v return true }) @@ -95,7 +95,7 @@ func TestExtendLease(t *testing.T) { require.EqualError(t, err, testCase.expectedErrMsg) } - expectedArgs := []interface{}{60, localhost, samplingLock, localhost} + expectedArgs := []any{60, localhost, samplingLock, localhost} assert.Equal(t, expectedArgs, args) }) }) @@ -162,8 +162,8 @@ func TestAcquire(t *testing.T) { firstQuery := &mocks.Query{} secondQuery := &mocks.Query{} - scanMatcher := func() interface{} { - scanFunc := func(args []interface{}) bool { + scanMatcher := func() any { + scanFunc := func(args []any) bool { for i, arg := range args { if ptr, ok := arg.(*string); ok { *ptr = testCase.retVals[i] @@ -228,8 +228,8 @@ func TestForfeit(t *testing.T) { query := &mocks.Query{} query.On("ScanCAS", matchEverything()).Return(testCase.applied, testCase.errScan) - var args []interface{} - captureArgs := mock.MatchedBy(func(v []interface{}) bool { + var args []any + captureArgs := mock.MatchedBy(func(v []any) bool { args = v return true }) @@ -259,12 +259,12 @@ func TestForfeit(t *testing.T) { } } -func matchEverything() interface{} { - return mock.MatchedBy(func(v []interface{}) bool { return true }) +func matchEverything() any { + return mock.MatchedBy(func(v []any) bool { return true }) } // stringMatcher can match a string argument when it contains a specific substring q -func stringMatcher(q string) interface{} { +func stringMatcher(q string) any { matchFunc := func(s string) bool { return strings.Contains(s, q) } diff --git a/plugin/storage/cassandra/dependencystore/storage_test.go b/plugin/storage/cassandra/dependencystore/storage_test.go index e6ce6e1c936..eca789ba154 100644 --- a/plugin/storage/cassandra/dependencystore/storage_test.go +++ b/plugin/storage/cassandra/dependencystore/storage_test.go @@ -95,8 +95,8 @@ func TestDependencyStoreWrite(t *testing.T) { query := &mocks.Query{} query.On("Exec").Return(nil) - var args []interface{} - captureArgs := mock.MatchedBy(func(v []interface{}) bool { + var args []any + captureArgs := mock.MatchedBy(func(v []any) bool { args = v return true }) @@ -190,7 +190,7 @@ func TestDependencyStoreGetDependencies(t *testing.T) { testCase := tc // capture loop var t.Run(testCase.caption, func(t *testing.T) { withDepStore(testCase.version, func(s *depStorageTest) { - scanMatcher := func() interface{} { + scanMatcher := func() any { deps := [][]Dependency{ { {Parent: "a", Child: "b", CallCount: 1}, @@ -201,7 +201,7 @@ func TestDependencyStoreGetDependencies(t *testing.T) { {Parent: "b", Child: "c", CallCount: 1}, }, } - scanFunc := func(args []interface{}) bool { + scanFunc := func(args []any) bool { if len(deps) == 0 { return false } @@ -267,6 +267,6 @@ func TestGetBuckets(t *testing.T) { assert.Equal(t, expected, getBuckets(start, end)) } -func matchEverything() interface{} { - return mock.MatchedBy(func(v []interface{}) bool { return true }) +func matchEverything() any { + return mock.MatchedBy(func(v []any) bool { return true }) } diff --git a/plugin/storage/cassandra/samplingstore/storage_test.go b/plugin/storage/cassandra/samplingstore/storage_test.go index eb571e5b648..9de051d15dc 100644 --- a/plugin/storage/cassandra/samplingstore/storage_test.go +++ b/plugin/storage/cassandra/samplingstore/storage_test.go @@ -62,8 +62,8 @@ func TestInsertThroughput(t *testing.T) { query := &mocks.Query{} query.On("Exec").Return(nil) - var args []interface{} - captureArgs := mock.MatchedBy(func(v []interface{}) bool { + var args []any + captureArgs := mock.MatchedBy(func(v []any) bool { args = v return true }) @@ -100,8 +100,8 @@ func TestInsertProbabilitiesAndQPS(t *testing.T) { query := &mocks.Query{} query.On("Exec").Return(nil) - var args []interface{} - captureArgs := mock.MatchedBy(func(v []interface{}) bool { + var args []any + captureArgs := mock.MatchedBy(func(v []any) bool { args = v return true }) @@ -164,12 +164,12 @@ func TestGetThroughput(t *testing.T) { testCase := tc // capture loop var t.Run(testCase.caption, func(t *testing.T) { withSamplingStore(func(s *samplingStoreTest) { - scanMatcher := func() interface{} { + scanMatcher := func() any { throughputStr := []string{ "\"svc,withcomma\",\"op,withcomma\",40,\"0.1,\"\n", "svc,op,50,\n", } - scanFunc := func(args []interface{}) bool { + scanFunc := func(args []any) bool { if len(throughputStr) == 0 { return false } @@ -245,11 +245,11 @@ func TestGetLatestProbabilities(t *testing.T) { testCase := tc // capture loop var t.Run(testCase.caption, func(t *testing.T) { withSamplingStore(func(s *samplingStoreTest) { - scanMatcher := func() interface{} { + scanMatcher := func() any { probabilitiesStr := []string{ "svc,op,0.84,40\n", } - scanFunc := func(args []interface{}) bool { + scanFunc := func(args []any) bool { if len(probabilitiesStr) == 0 { return false } @@ -288,8 +288,8 @@ func TestGetLatestProbabilities(t *testing.T) { } } -func matchEverything() interface{} { - return mock.MatchedBy(func(v []interface{}) bool { return true }) +func matchEverything() any { + return mock.MatchedBy(func(v []any) bool { return true }) } func TestGenerateRandomBucket(t *testing.T) { diff --git a/plugin/storage/cassandra/spanstore/matchers_test.go b/plugin/storage/cassandra/spanstore/matchers_test.go index 73250ffffc2..14904f70231 100644 --- a/plugin/storage/cassandra/spanstore/matchers_test.go +++ b/plugin/storage/cassandra/spanstore/matchers_test.go @@ -21,13 +21,13 @@ import ( "github.com/stretchr/testify/mock" ) -func matchOnce() interface{} { +func matchOnce() any { return matchOnceWithSideEffect(nil) } -func matchOnceWithSideEffect(fn func(v []interface{})) interface{} { +func matchOnceWithSideEffect(fn func(v []any)) any { var matched bool - return mock.MatchedBy(func(v []interface{}) bool { + return mock.MatchedBy(func(v []any) bool { if matched { return false } @@ -39,12 +39,12 @@ func matchOnceWithSideEffect(fn func(v []interface{})) interface{} { }) } -func matchEverything() interface{} { - return mock.MatchedBy(func(v []interface{}) bool { return true }) +func matchEverything() any { + return mock.MatchedBy(func(v []any) bool { return true }) } // stringMatcher can match a string argument when it contains a specific substring q -func stringMatcher(q string) interface{} { +func stringMatcher(q string) any { matchFunc := func(s string) bool { return strings.Contains(s, q) } diff --git a/plugin/storage/cassandra/spanstore/operation_names_test.go b/plugin/storage/cassandra/spanstore/operation_names_test.go index 4f096a3b117..63ccfd005e1 100644 --- a/plugin/storage/cassandra/spanstore/operation_names_test.go +++ b/plugin/storage/cassandra/spanstore/operation_names_test.go @@ -88,11 +88,11 @@ func TestOperationNamesStorageWrite(t *testing.T) { query2 := &mocks.Query{} if test.schemaVersion == previousVersion { - query.On("Bind", []interface{}{"service-a", "Operation-b"}).Return(query1) - query.On("Bind", []interface{}{"service-c", "operation-d"}).Return(query2) + query.On("Bind", []any{"service-a", "Operation-b"}).Return(query1) + query.On("Bind", []any{"service-c", "operation-d"}).Return(query2) } else { - query.On("Bind", []interface{}{"service-a", "", "Operation-b"}).Return(query1) - query.On("Bind", []interface{}{"service-c", "", "operation-d"}).Return(query2) + query.On("Bind", []any{"service-a", "", "Operation-b"}).Return(query1) + query.On("Bind", []any{"service-c", "", "operation-d"}).Return(query2) } query1.On("Exec").Return(nil) @@ -164,14 +164,14 @@ func TestOperationNamesStorageGetServices(t *testing.T) { t.Run(test.name, func(t *testing.T) { withOperationNamesStorage(0, test.schemaVersion, func(s *operationNameStorageTest) { var matched bool - matchOnce := mock.MatchedBy(func(v []interface{}) bool { + matchOnce := mock.MatchedBy(func(v []any) bool { if matched { return false } matched = true return true }) - matchEverything := mock.MatchedBy(func(v []interface{}) bool { return true }) + matchEverything := mock.MatchedBy(func(v []any) bool { return true }) iter := &mocks.Iterator{} iter.On("Scan", matchOnce).Return(true) diff --git a/plugin/storage/cassandra/spanstore/reader_test.go b/plugin/storage/cassandra/spanstore/reader_test.go index 65ebe9e198d..a305ef97967 100644 --- a/plugin/storage/cassandra/spanstore/reader_test.go +++ b/plugin/storage/cassandra/spanstore/reader_test.go @@ -110,8 +110,8 @@ func TestSpanReaderGetOperations(t *testing.T) { } func TestSpanReaderGetTrace(t *testing.T) { - badScan := func() interface{} { - return matchOnceWithSideEffect(func(args []interface{}) { + badScan := func() any { + return matchOnceWithSideEffect(func(args []any) { for _, arg := range args { if v, ok := arg.(*[]dbmodel.KeyValue); ok { *v = []dbmodel.KeyValue{ @@ -125,7 +125,7 @@ func TestSpanReaderGetTrace(t *testing.T) { } testCases := []struct { - scanner interface{} + scanner any closeErr error expectedErr string }{ @@ -310,12 +310,12 @@ func TestSpanReaderFindTraces(t *testing.T) { t.Run(testCase.caption, func(t *testing.T) { withSpanReader(t, func(r *spanReaderTest) { // scanMatcher can match Iter.Scan() parameters and set trace ID fields - scanMatcher := func(name string) interface{} { + scanMatcher := func(name string) any { traceIDs := []dbmodel.TraceID{ dbmodel.TraceIDFromDomain(model.NewTraceID(0, 1)), dbmodel.TraceIDFromDomain(model.NewTraceID(0, 2)), } - scanFunc := func(args []interface{}) bool { + scanFunc := func(args []any) bool { if len(traceIDs) == 0 { return false } diff --git a/plugin/storage/cassandra/spanstore/service_names_test.go b/plugin/storage/cassandra/spanstore/service_names_test.go index af30d0f2ce7..3c35dc402af 100644 --- a/plugin/storage/cassandra/spanstore/service_names_test.go +++ b/plugin/storage/cassandra/spanstore/service_names_test.go @@ -65,13 +65,13 @@ func TestServiceNamesStorageWrite(t *testing.T) { query := &mocks.Query{} query1 := &mocks.Query{} query2 := &mocks.Query{} - query.On("Bind", []interface{}{"service-a"}).Return(query1) - query.On("Bind", []interface{}{"service-b"}).Return(query2) + query.On("Bind", []any{"service-a"}).Return(query1) + query.On("Bind", []any{"service-b"}).Return(query2) query1.On("Exec").Return(nil) query2.On("Exec").Return(execError) query2.On("String").Return("select from service_names") - var emptyArgs []interface{} + var emptyArgs []any s.session.On("Query", mock.AnythingOfType("string"), emptyArgs).Return(query) err := s.storage.Write("service-a") @@ -111,14 +111,14 @@ func TestServiceNamesStorageGetServices(t *testing.T) { scanError := errors.New("scan error") var writeCacheTTL time.Duration var matched bool - matchOnce := mock.MatchedBy(func(v []interface{}) bool { + matchOnce := mock.MatchedBy(func(v []any) bool { if matched { return false } matched = true return true }) - matchEverything := mock.MatchedBy(func(v []interface{}) bool { return true }) + matchEverything := mock.MatchedBy(func(v []any) bool { return true }) for _, expErr := range []error{nil, scanError} { withServiceNamesStorage(writeCacheTTL, func(s *serviceNameStorageTest) { iter := &mocks.Iterator{} @@ -129,7 +129,7 @@ func TestServiceNamesStorageGetServices(t *testing.T) { query := &mocks.Query{} query.On("Iter").Return(iter) - var emptyArgs []interface{} + var emptyArgs []any s.session.On("Query", mock.AnythingOfType("string"), emptyArgs).Return(query) services, err := s.storage.GetServices() diff --git a/plugin/storage/es/dependencystore/storage_test.go b/plugin/storage/es/dependencystore/storage_test.go index a147535bbbf..5118d919962 100644 --- a/plugin/storage/es/dependencystore/storage_test.go +++ b/plugin/storage/es/dependencystore/storage_test.go @@ -144,7 +144,7 @@ func TestGetDependencies(t *testing.T) { expectedOutput []model.DependencyLink indexPrefix string maxDocCount int - indices []interface{} + indices []any }{ { searchResult: createSearchResult(goodDependencies), @@ -155,24 +155,24 @@ func TestGetDependencies(t *testing.T) { CallCount: 12, }, }, - indices: []interface{}{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, + indices: []any{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, maxDocCount: 1000, // can be anything, assertion will check this value is used in search query. }, { searchResult: createSearchResult(badDependencies), expectedError: "unmarshalling ElasticSearch documents failed", - indices: []interface{}{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, + indices: []any{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, }, { searchError: errors.New("search failure"), expectedError: "failed to search for dependencies: search failure", - indices: []interface{}{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, + indices: []any{"jaeger-dependencies-1995-04-21", "jaeger-dependencies-1995-04-20"}, }, { searchError: errors.New("search failure"), expectedError: "failed to search for dependencies: search failure", indexPrefix: "foo", - indices: []interface{}{"foo-jaeger-dependencies-1995-04-21", "foo-jaeger-dependencies-1995-04-20"}, + indices: []any{"foo-jaeger-dependencies-1995-04-21", "foo-jaeger-dependencies-1995-04-20"}, }, } for _, testCase := range testCases { @@ -285,7 +285,7 @@ func TestGetWriteIndex(t *testing.T) { } // stringMatcher can match a string argument when it contains a specific substring q -func stringMatcher(q string) interface{} { +func stringMatcher(q string) any { matchFunc := func(s string) bool { return strings.Contains(s, q) } diff --git a/plugin/storage/es/samplingstore/storage_test.go b/plugin/storage/es/samplingstore/storage_test.go index f0d171119c0..97920a75dec 100644 --- a/plugin/storage/es/samplingstore/storage_test.go +++ b/plugin/storage/es/samplingstore/storage_test.go @@ -449,7 +449,7 @@ func createSearchResult(rawJsonStr string) *elastic.SearchResult { return searchResult } -func stringMatcher(q string) interface{} { +func stringMatcher(q string) any { matchFunc := func(s string) bool { return strings.Contains(s, q) } diff --git a/plugin/storage/es/spanstore/dbmodel/from_domain.go b/plugin/storage/es/spanstore/dbmodel/from_domain.go index f21a84925bd..daa90c16e49 100644 --- a/plugin/storage/es/spanstore/dbmodel/from_domain.go +++ b/plugin/storage/es/spanstore/dbmodel/from_domain.go @@ -85,13 +85,13 @@ func (fd FromDomain) convertRefType(refType model.SpanRefType) ReferenceType { return ChildOf } -func (fd FromDomain) convertKeyValuesString(keyValues model.KeyValues) ([]KeyValue, map[string]interface{}) { - var tagsMap map[string]interface{} +func (fd FromDomain) convertKeyValuesString(keyValues model.KeyValues) ([]KeyValue, map[string]any) { + var tagsMap map[string]any var kvs []KeyValue for _, kv := range keyValues { if kv.GetVType() != model.BinaryType && (fd.allTagsAsFields || fd.tagKeysAsFields[kv.Key]) { if tagsMap == nil { - tagsMap = map[string]interface{}{} + tagsMap = map[string]any{} } tagsMap[strings.ReplaceAll(kv.Key, ".", fd.tagDotReplacement)] = kv.Value() } else { diff --git a/plugin/storage/es/spanstore/dbmodel/from_domain_test.go b/plugin/storage/es/spanstore/dbmodel/from_domain_test.go index 4780885bc87..b57d8383e70 100644 --- a/plugin/storage/es/spanstore/dbmodel/from_domain_test.go +++ b/plugin/storage/es/spanstore/dbmodel/from_domain_test.go @@ -63,7 +63,7 @@ func loadFixtures(t *testing.T, i int) ([]byte, []byte) { return inStr, outStr } -func testJSONEncoding(t *testing.T, i int, expectedStr []byte, object interface{}) { +func testJSONEncoding(t *testing.T, i int, expectedStr []byte, object any) { buf := &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetIndent("", " ") @@ -101,7 +101,7 @@ func TestTagMap(t *testing.T) { assert.Len(t, dbSpan.Process.Tags, 1) assert.Equal(t, "foo", dbSpan.Process.Tags[0].Key) - tagsMap := map[string]interface{}{} + tagsMap := map[string]any{} tagsMap["a"] = true tagsMap["b:b"] = int64(1) assert.Equal(t, tagsMap, dbSpan.Tag) diff --git a/plugin/storage/es/spanstore/dbmodel/model.go b/plugin/storage/es/spanstore/dbmodel/model.go index e2b0e01970e..db2fffac409 100644 --- a/plugin/storage/es/spanstore/dbmodel/model.go +++ b/plugin/storage/es/spanstore/dbmodel/model.go @@ -61,9 +61,9 @@ type Span struct { Duration uint64 `json:"duration"` // microseconds Tags []KeyValue `json:"tags"` // Alternative representation of tags for better kibana support - Tag map[string]interface{} `json:"tag,omitempty"` - Logs []Log `json:"logs"` - Process Process `json:"process,omitempty"` + Tag map[string]any `json:"tag,omitempty"` + Logs []Log `json:"logs"` + Process Process `json:"process,omitempty"` } // Reference is a reference from one span to another @@ -78,7 +78,7 @@ type Process struct { ServiceName string `json:"serviceName"` Tags []KeyValue `json:"tags"` // Alternative representation of tags for better kibana support - Tag map[string]interface{} `json:"tag,omitempty"` + Tag map[string]any `json:"tag,omitempty"` } // Log is a log emitted in a span @@ -89,9 +89,9 @@ type Log struct { // KeyValue is a key-value pair with typed value. type KeyValue struct { - Key string `json:"key"` - Type ValueType `json:"type,omitempty"` - Value interface{} `json:"value"` + Key string `json:"key"` + Type ValueType `json:"type,omitempty"` + Value any `json:"value"` } // Service is the JSON struct for service:operation documents in ElasticSearch diff --git a/plugin/storage/es/spanstore/dbmodel/to_domain.go b/plugin/storage/es/spanstore/dbmodel/to_domain.go index ccf894871e6..cab2208edd1 100644 --- a/plugin/storage/es/spanstore/dbmodel/to_domain.go +++ b/plugin/storage/es/spanstore/dbmodel/to_domain.go @@ -147,7 +147,7 @@ func (td ToDomain) convertKeyValues(tags []KeyValue) ([]model.KeyValue, error) { return retMe, nil } -func (td ToDomain) convertTagFields(tagsMap map[string]interface{}) ([]model.KeyValue, error) { +func (td ToDomain) convertTagFields(tagsMap map[string]any) ([]model.KeyValue, error) { kvs := make([]model.KeyValue, len(tagsMap)) i := 0 for k, v := range tagsMap { @@ -161,7 +161,7 @@ func (td ToDomain) convertTagFields(tagsMap map[string]interface{}) ([]model.Key return kvs, nil } -func (td ToDomain) convertTagField(k string, v interface{}) (model.KeyValue, error) { +func (td ToDomain) convertTagField(k string, v any) (model.KeyValue, error) { dKey := td.ReplaceDotReplacement(k) switch val := v.(type) { case int64: diff --git a/plugin/storage/es/spanstore/dbmodel/to_domain_test.go b/plugin/storage/es/spanstore/dbmodel/to_domain_test.go index bdafe94ce2f..cba408a1143 100644 --- a/plugin/storage/es/spanstore/dbmodel/to_domain_test.go +++ b/plugin/storage/es/spanstore/dbmodel/to_domain_test.go @@ -285,14 +285,14 @@ func TestFailureBadParentSpanID(t *testing.T) { func TestFailureBadSpanFieldTag(t *testing.T) { badParentSpanIDESSpan, err := loadESSpanFixture(1) require.NoError(t, err) - badParentSpanIDESSpan.Tag = map[string]interface{}{"foo": struct{}{}} + badParentSpanIDESSpan.Tag = map[string]any{"foo": struct{}{}} failingSpanTransformAnyMsg(t, &badParentSpanIDESSpan) } func TestFailureBadProcessFieldTag(t *testing.T) { badParentSpanIDESSpan, err := loadESSpanFixture(1) require.NoError(t, err) - badParentSpanIDESSpan.Process.Tag = map[string]interface{}{"foo": struct{}{}} + badParentSpanIDESSpan.Process.Tag = map[string]any{"foo": struct{}{}} failingSpanTransformAnyMsg(t, &badParentSpanIDESSpan) } @@ -312,25 +312,25 @@ func CompareModelSpans(t *testing.T, expected *model.Span, actual *model.Span) { func TestTagsMap(t *testing.T) { tests := []struct { - fieldTags map[string]interface{} + fieldTags map[string]any expected []model.KeyValue err error }{ - {fieldTags: map[string]interface{}{"bool:bool": true}, expected: []model.KeyValue{model.Bool("bool.bool", true)}}, - {fieldTags: map[string]interface{}{"int.int": int64(1)}, expected: []model.KeyValue{model.Int64("int.int", 1)}}, - {fieldTags: map[string]interface{}{"int:int": int64(2)}, expected: []model.KeyValue{model.Int64("int.int", 2)}}, - {fieldTags: map[string]interface{}{"float": float64(1.1)}, expected: []model.KeyValue{model.Float64("float", 1.1)}}, - {fieldTags: map[string]interface{}{"float": float64(123)}, expected: []model.KeyValue{model.Float64("float", float64(123))}}, - {fieldTags: map[string]interface{}{"float": float64(123.0)}, expected: []model.KeyValue{model.Float64("float", float64(123.0))}}, - {fieldTags: map[string]interface{}{"float:float": float64(123)}, expected: []model.KeyValue{model.Float64("float.float", float64(123))}}, - {fieldTags: map[string]interface{}{"json_number:int": json.Number("123")}, expected: []model.KeyValue{model.Int64("json_number.int", 123)}}, - {fieldTags: map[string]interface{}{"json_number:float": json.Number("123.0")}, expected: []model.KeyValue{model.Float64("json_number.float", float64(123.0))}}, - {fieldTags: map[string]interface{}{"json_number:err": json.Number("foo")}, err: fmt.Errorf("invalid tag type in foo: strconv.ParseFloat: parsing \"foo\": invalid syntax")}, - {fieldTags: map[string]interface{}{"str": "foo"}, expected: []model.KeyValue{model.String("str", "foo")}}, - {fieldTags: map[string]interface{}{"str:str": "foo"}, expected: []model.KeyValue{model.String("str.str", "foo")}}, - {fieldTags: map[string]interface{}{"binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary", []byte("foo"))}}, - {fieldTags: map[string]interface{}{"binary:binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary.binary", []byte("foo"))}}, - {fieldTags: map[string]interface{}{"unsupported": struct{}{}}, err: fmt.Errorf("invalid tag type in %+v", struct{}{})}, + {fieldTags: map[string]any{"bool:bool": true}, expected: []model.KeyValue{model.Bool("bool.bool", true)}}, + {fieldTags: map[string]any{"int.int": int64(1)}, expected: []model.KeyValue{model.Int64("int.int", 1)}}, + {fieldTags: map[string]any{"int:int": int64(2)}, expected: []model.KeyValue{model.Int64("int.int", 2)}}, + {fieldTags: map[string]any{"float": float64(1.1)}, expected: []model.KeyValue{model.Float64("float", 1.1)}}, + {fieldTags: map[string]any{"float": float64(123)}, expected: []model.KeyValue{model.Float64("float", float64(123))}}, + {fieldTags: map[string]any{"float": float64(123.0)}, expected: []model.KeyValue{model.Float64("float", float64(123.0))}}, + {fieldTags: map[string]any{"float:float": float64(123)}, expected: []model.KeyValue{model.Float64("float.float", float64(123))}}, + {fieldTags: map[string]any{"json_number:int": json.Number("123")}, expected: []model.KeyValue{model.Int64("json_number.int", 123)}}, + {fieldTags: map[string]any{"json_number:float": json.Number("123.0")}, expected: []model.KeyValue{model.Float64("json_number.float", float64(123.0))}}, + {fieldTags: map[string]any{"json_number:err": json.Number("foo")}, err: fmt.Errorf("invalid tag type in foo: strconv.ParseFloat: parsing \"foo\": invalid syntax")}, + {fieldTags: map[string]any{"str": "foo"}, expected: []model.KeyValue{model.String("str", "foo")}}, + {fieldTags: map[string]any{"str:str": "foo"}, expected: []model.KeyValue{model.String("str.str", "foo")}}, + {fieldTags: map[string]any{"binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary", []byte("foo"))}}, + {fieldTags: map[string]any{"binary:binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary.binary", []byte("foo"))}}, + {fieldTags: map[string]any{"unsupported": struct{}{}}, err: fmt.Errorf("invalid tag type in %+v", struct{}{})}, } converter := NewToDomain(":") for i, test := range tests { diff --git a/plugin/storage/es/spanstore/reader_test.go b/plugin/storage/es/spanstore/reader_test.go index 5cd4f68ad9e..f989ca29616 100644 --- a/plugin/storage/es/spanstore/reader_test.go +++ b/plugin/storage/es/spanstore/reader_test.go @@ -635,12 +635,12 @@ func testGet(typ string, t *testing.T) { searchResult *elastic.SearchResult searchError error expectedError func() string - expectedOutput map[string]interface{} + expectedOutput map[string]any }{ { caption: typ + " full behavior", searchResult: &elastic.SearchResult{Aggregations: elastic.Aggregations(goodAggregations)}, - expectedOutput: map[string]interface{}{ + expectedOutput: map[string]any{ operationsAggregation: []spanstore.Operation{{Name: "123"}}, "default": []string{"123"}, }, @@ -686,7 +686,7 @@ func testGet(typ string, t *testing.T) { } } -func returnSearchFunc(typ string, r *spanReaderTest) (interface{}, error) { +func returnSearchFunc(typ string, r *spanReaderTest) (any, error) { switch typ { case servicesAggregation: return r.reader.GetServices(context.Background()) @@ -1072,10 +1072,10 @@ func TestSpanReader_buildTraceIDAggregation(t *testing.T) { actual, err := traceIDAggregation.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal([]byte(expectedStr), &expected) - expected["terms"].(map[string]interface{})["size"] = 123 - expected["terms"].(map[string]interface{})["order"] = []interface{}{map[string]string{"startTime": "desc"}} + expected["terms"].(map[string]any)["size"] = 123 + expected["terms"].(map[string]any)["order"] = []any{map[string]string{"startTime": "desc"}} assert.EqualValues(t, expected, actual) }) } @@ -1126,11 +1126,11 @@ func TestSpanReader_buildDurationQuery(t *testing.T) { actual, err := durationQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal([]byte(expectedStr), &expected) // We need to do this because we cannot process a json into uint64. - expected["range"].(map[string]interface{})["duration"].(map[string]interface{})["from"] = model.DurationAsMicroseconds(durationMin) - expected["range"].(map[string]interface{})["duration"].(map[string]interface{})["to"] = model.DurationAsMicroseconds(durationMax) + expected["range"].(map[string]any)["duration"].(map[string]any)["from"] = model.DurationAsMicroseconds(durationMin) + expected["range"].(map[string]any)["duration"].(map[string]any)["to"] = model.DurationAsMicroseconds(durationMax) assert.EqualValues(t, expected, actual) }) @@ -1151,11 +1151,11 @@ func TestSpanReader_buildStartTimeQuery(t *testing.T) { actual, err := durationQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal([]byte(expectedStr), &expected) // We need to do this because we cannot process a json into uint64. - expected["range"].(map[string]interface{})["startTimeMillis"].(map[string]interface{})["from"] = model.TimeAsEpochMicroseconds(startTimeMin) / 1000 - expected["range"].(map[string]interface{})["startTimeMillis"].(map[string]interface{})["to"] = model.TimeAsEpochMicroseconds(startTimeMax) / 1000 + expected["range"].(map[string]any)["startTimeMillis"].(map[string]any)["from"] = model.TimeAsEpochMicroseconds(startTimeMin) / 1000 + expected["range"].(map[string]any)["startTimeMillis"].(map[string]any)["to"] = model.TimeAsEpochMicroseconds(startTimeMax) / 1000 assert.EqualValues(t, expected, actual) }) @@ -1168,7 +1168,7 @@ func TestSpanReader_buildServiceNameQuery(t *testing.T) { actual, err := serviceNameQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal([]byte(expectedStr), &expected) assert.EqualValues(t, expected, actual) @@ -1182,7 +1182,7 @@ func TestSpanReader_buildOperationNameQuery(t *testing.T) { actual, err := operationNameQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal([]byte(expectedStr), &expected) assert.EqualValues(t, expected, actual) @@ -1197,7 +1197,7 @@ func TestSpanReader_buildTagQuery(t *testing.T) { actual, err := tagQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal(inStr, &expected) assert.EqualValues(t, expected, actual) @@ -1212,7 +1212,7 @@ func TestSpanReader_buildTagRegexQuery(t *testing.T) { actual, err := tagQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal(inStr, &expected) assert.EqualValues(t, expected, actual) @@ -1227,7 +1227,7 @@ func TestSpanReader_buildTagRegexEscapedQuery(t *testing.T) { actual, err := tagQuery.Source() require.NoError(t, err) - expected := make(map[string]interface{}) + expected := make(map[string]any) json.Unmarshal(inStr, &expected) assert.EqualValues(t, expected, actual) @@ -1340,7 +1340,7 @@ func TestTerminateAfterNotSet(t *testing.T) { sp, err := searchSource.Source() require.NoError(t, err) - searchParams, ok := sp.(map[string]interface{}) + searchParams, ok := sp.(map[string]any) require.True(t, ok) termAfter, ok := searchParams["terminate_after"] @@ -1350,7 +1350,7 @@ func TestTerminateAfterNotSet(t *testing.T) { query, ok := searchParams["query"] require.True(t, ok) - queryMap, ok := query.(map[string]interface{}) + queryMap, ok := query.(map[string]any) require.True(t, ok) _, ok = queryMap["match_all"] require.True(t, ok) diff --git a/plugin/storage/es/spanstore/writer_test.go b/plugin/storage/es/spanstore/writer_test.go index 2d6ad2f812e..4630c94fcff 100644 --- a/plugin/storage/es/spanstore/writer_test.go +++ b/plugin/storage/es/spanstore/writer_test.go @@ -371,8 +371,8 @@ func TestNewSpanTags(t *testing.T) { AllTagsAsFields: true, }), expected: dbmodel.Span{ - Tag: map[string]interface{}{"foo": "bar"}, Tags: []dbmodel.KeyValue{}, - Process: dbmodel.Process{Tag: map[string]interface{}{"bar": "baz"}, Tags: []dbmodel.KeyValue{}}, + Tag: map[string]any{"foo": "bar"}, Tags: []dbmodel.KeyValue{}, + Process: dbmodel.Process{Tag: map[string]any{"bar": "baz"}, Tags: []dbmodel.KeyValue{}}, }, name: "allTagsAsFields", }, @@ -382,8 +382,8 @@ func TestNewSpanTags(t *testing.T) { TagKeysAsFields: []string{"foo", "bar", "rere"}, }), expected: dbmodel.Span{ - Tag: map[string]interface{}{"foo": "bar"}, Tags: []dbmodel.KeyValue{}, - Process: dbmodel.Process{Tag: map[string]interface{}{"bar": "baz"}, Tags: []dbmodel.KeyValue{}}, + Tag: map[string]any{"foo": "bar"}, Tags: []dbmodel.KeyValue{}, + Process: dbmodel.Process{Tag: map[string]any{"bar": "baz"}, Tags: []dbmodel.KeyValue{}}, }, name: "definedTagNames", }, @@ -485,7 +485,7 @@ func TestSpanWriterParamsTTL(t *testing.T) { } // stringMatcher can match a string argument when it contains a specific substring q -func stringMatcher(q string) interface{} { +func stringMatcher(q string) any { matchFunc := func(s string) bool { return strings.Contains(s, q) } diff --git a/plugin/storage/integration/integration.go b/plugin/storage/integration/integration.go index d85616987ca..28b8546004e 100644 --- a/plugin/storage/integration/integration.go +++ b/plugin/storage/integration/integration.go @@ -390,7 +390,7 @@ func LoadAndParseQueryTestCases(t *testing.T, queriesFile string) []*QueryFixtur return queries } -func loadAndParseJSON(t *testing.T, path string, object interface{}) { +func loadAndParseJSON(t *testing.T, path string, object any) { // #nosec inStr, err := fixtures.ReadFile(path) require.NoError(t, err, "Not expecting error when loading fixture %s", path) diff --git a/storage/spanstore/downsampling_writer.go b/storage/spanstore/downsampling_writer.go index dd354e4d080..b6463edac81 100644 --- a/storage/spanstore/downsampling_writer.go +++ b/storage/spanstore/downsampling_writer.go @@ -100,7 +100,7 @@ func NewSampler(ratio float64, hashSalt string) *Sampler { } hashSaltBytes := []byte(hashSalt) pool := &sync.Pool{ - New: func() interface{} { + New: func() any { buffer := make([]byte, len(hashSaltBytes)+traceIDByteSize) copy(buffer, hashSaltBytes) return &hasher{