diff --git a/attributes/attributes.go b/attributes/attributes.go index 49712aca33ae..712fef4d0fb9 100644 --- a/attributes/attributes.go +++ b/attributes/attributes.go @@ -34,26 +34,26 @@ import ( // key/value pairs. Keys must be hashable, and users should define their own // types for keys. Values should not be modified after they are added to an // Attributes or if they were received from one. If values implement 'Equal(o -// interface{}) bool', it will be called by (*Attributes).Equal to determine -// whether two values with the same key should be considered equal. +// any) bool', it will be called by (*Attributes).Equal to determine whether +// two values with the same key should be considered equal. type Attributes struct { - m map[interface{}]interface{} + m map[any]any } // New returns a new Attributes containing the key/value pair. -func New(key, value interface{}) *Attributes { - return &Attributes{m: map[interface{}]interface{}{key: value}} +func New(key, value any) *Attributes { + return &Attributes{m: map[any]any{key: value}} } // WithValue returns a new Attributes containing the previous keys and values // and the new key/value pair. If the same key appears multiple times, the // last value overwrites all previous values for that key. To remove an // existing key, use a nil value. value should not be modified later. -func (a *Attributes) WithValue(key, value interface{}) *Attributes { +func (a *Attributes) WithValue(key, value any) *Attributes { if a == nil { return New(key, value) } - n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+1)} + n := &Attributes{m: make(map[any]any, len(a.m)+1)} for k, v := range a.m { n.m[k] = v } @@ -63,20 +63,19 @@ func (a *Attributes) WithValue(key, value interface{}) *Attributes { // Value returns the value associated with these attributes for key, or nil if // no value is associated with key. The returned value should not be modified. -func (a *Attributes) Value(key interface{}) interface{} { +func (a *Attributes) Value(key any) any { if a == nil { return nil } return a.m[key] } -// Equal returns whether a and o are equivalent. If 'Equal(o interface{}) -// bool' is implemented for a value in the attributes, it is called to -// determine if the value matches the one stored in the other attributes. If -// Equal is not implemented, standard equality is used to determine if the two -// values are equal. Note that some types (e.g. maps) aren't comparable by -// default, so they must be wrapped in a struct, or in an alias type, with Equal -// defined. +// Equal returns whether a and o are equivalent. If 'Equal(o any) bool' is +// implemented for a value in the attributes, it is called to determine if the +// value matches the one stored in the other attributes. If Equal is not +// implemented, standard equality is used to determine if the two values are +// equal. Note that some types (e.g. maps) aren't comparable by default, so +// they must be wrapped in a struct, or in an alias type, with Equal defined. func (a *Attributes) Equal(o *Attributes) bool { if a == nil && o == nil { return true @@ -93,7 +92,7 @@ func (a *Attributes) Equal(o *Attributes) bool { // o missing element of a return false } - if eq, ok := v.(interface{ Equal(o interface{}) bool }); ok { + if eq, ok := v.(interface{ Equal(o any) bool }); ok { if !eq.Equal(ov) { return false } @@ -122,7 +121,7 @@ func (a *Attributes) String() string { return sb.String() } -func str(x interface{}) string { +func str(x any) string { if v, ok := x.(fmt.Stringer); ok { return v.String() } else if v, ok := x.(string); ok { diff --git a/attributes/attributes_test.go b/attributes/attributes_test.go index 02d5b24f3df1..e4db92177a93 100644 --- a/attributes/attributes_test.go +++ b/attributes/attributes_test.go @@ -29,7 +29,7 @@ type stringVal struct { s string } -func (s stringVal) Equal(o interface{}) bool { +func (s stringVal) Equal(o any) bool { os, ok := o.(stringVal) return ok && s.s == os.s } diff --git a/authz/audit/stdout/stdout_logger.go b/authz/audit/stdout/stdout_logger.go index c4ba21fa4682..f9bfc2d7d61e 100644 --- a/authz/audit/stdout/stdout_logger.go +++ b/authz/audit/stdout/stdout_logger.go @@ -56,7 +56,7 @@ type logger struct { // Log marshals the audit.Event to json and prints it to standard output. func (l *logger) Log(event *audit.Event) { - jsonContainer := map[string]interface{}{ + jsonContainer := map[string]any{ "grpc_audit_log": convertEvent(event), } jsonBytes, err := json.Marshal(jsonContainer) diff --git a/authz/audit/stdout/stdout_logger_test.go b/authz/audit/stdout/stdout_logger_test.go index a389b942e2c7..02f9860c5315 100644 --- a/authz/audit/stdout/stdout_logger_test.go +++ b/authz/audit/stdout/stdout_logger_test.go @@ -72,11 +72,11 @@ func (s) TestStdoutLogger_Log(t *testing.T) { auditLogger.Log(test.event) - var container map[string]interface{} + var container map[string]any if err := json.Unmarshal(buf.Bytes(), &container); err != nil { t.Fatalf("Failed to unmarshal audit log event: %v", err) } - innerEvent := extractEvent(container["grpc_audit_log"].(map[string]interface{})) + innerEvent := extractEvent(container["grpc_audit_log"].(map[string]any)) if innerEvent.Timestamp == "" { t.Fatalf("Resulted event has no timestamp: %v", innerEvent) } @@ -116,7 +116,7 @@ func (s) TestStdoutLoggerBuilder_Registration(t *testing.T) { // extractEvent extracts an stdout.event from a map // unmarshalled from a logged json message. -func extractEvent(container map[string]interface{}) event { +func extractEvent(container map[string]any) event { return event{ FullMethodName: container["rpc_method"].(string), Principal: container["principal"].(string), diff --git a/authz/grpc_authz_server_interceptors.go b/authz/grpc_authz_server_interceptors.go index 3e5f598a97d1..8dfc373fdb66 100644 --- a/authz/grpc_authz_server_interceptors.go +++ b/authz/grpc_authz_server_interceptors.go @@ -58,7 +58,7 @@ func NewStatic(authzPolicy string) (*StaticInterceptor, error) { // UnaryInterceptor intercepts incoming Unary RPC requests. // Only authorized requests are allowed to pass. Otherwise, an unauthorized // error is returned to the client. -func (i *StaticInterceptor) UnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func (i *StaticInterceptor) UnaryInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { err := i.engines.IsAuthorized(ctx) if err != nil { if status.Code(err) == codes.PermissionDenied { @@ -75,7 +75,7 @@ func (i *StaticInterceptor) UnaryInterceptor(ctx context.Context, req interface{ // StreamInterceptor intercepts incoming Stream RPC requests. // Only authorized requests are allowed to pass. Otherwise, an unauthorized // error is returned to the client. -func (i *StaticInterceptor) StreamInterceptor(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func (i *StaticInterceptor) StreamInterceptor(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := i.engines.IsAuthorized(ss.Context()) if err != nil { if status.Code(err) == codes.PermissionDenied { @@ -166,13 +166,13 @@ func (i *FileWatcherInterceptor) Close() { // UnaryInterceptor intercepts incoming Unary RPC requests. // Only authorized requests are allowed to pass. Otherwise, an unauthorized // error is returned to the client. -func (i *FileWatcherInterceptor) UnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func (i *FileWatcherInterceptor) UnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { return ((*StaticInterceptor)(atomic.LoadPointer(&i.internalInterceptor))).UnaryInterceptor(ctx, req, info, handler) } // StreamInterceptor intercepts incoming Stream RPC requests. // Only authorized requests are allowed to pass. Otherwise, an unauthorized // error is returned to the client. -func (i *FileWatcherInterceptor) StreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func (i *FileWatcherInterceptor) StreamInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { return ((*StaticInterceptor)(atomic.LoadPointer(&i.internalInterceptor))).StreamInterceptor(srv, ss, info, handler) } diff --git a/authz/rbac_translator_test.go b/authz/rbac_translator_test.go index 23b6fb669e9c..0de0d503252e 100644 --- a/authz/rbac_translator_test.go +++ b/authz/rbac_translator_test.go @@ -308,7 +308,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -342,7 +342,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_ON_ALLOW, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -404,7 +404,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_ON_DENY, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -438,7 +438,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_ON_DENY_AND_ALLOW, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -500,7 +500,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -534,7 +534,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -596,7 +596,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{"abc": 123, "xyz": "123"}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{"abc": 123, "xyz": "123"}, "stdout_logger")}, IsOptional: false, }, }, @@ -630,7 +630,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{"abc": 123, "xyz": "123"}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{"abc": 123, "xyz": "123"}, "stdout_logger")}, IsOptional: false, }, }, @@ -688,7 +688,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{"abc": 123, "xyz": map[string]interface{}{"abc": 123}}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{"abc": 123, "xyz": map[string]any{"abc": 123}}, "stdout_logger")}, IsOptional: false, }, }, @@ -792,7 +792,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_NONE, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -853,7 +853,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_ON_DENY, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -887,7 +887,7 @@ func TestTranslatePolicy(t *testing.T) { AuditLoggingOptions: &v3rbacpb.RBAC_AuditLoggingOptions{ AuditCondition: v3rbacpb.RBAC_AuditLoggingOptions_ON_DENY, LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ - {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]interface{}{}, "stdout_logger")}, + {AuditLogger: &v3corepb.TypedExtensionConfig{Name: "stdout_logger", TypedConfig: anyPbHelper(t, map[string]any{}, "stdout_logger")}, IsOptional: false, }, }, @@ -1034,7 +1034,7 @@ func TestTranslatePolicy(t *testing.T) { } } -func anyPbHelper(t *testing.T, in map[string]interface{}, name string) *anypb.Any { +func anyPbHelper(t *testing.T, in map[string]any, name string) *anypb.Any { t.Helper() pb, err := structpb.NewStruct(in) typedStruct := &v1xdsudpatypepb.TypedStruct{ diff --git a/balancer/balancer.go b/balancer/balancer.go index 3385b1ed6eec..b6377f445ad2 100644 --- a/balancer/balancer.go +++ b/balancer/balancer.go @@ -270,7 +270,7 @@ type DoneInfo struct { // trailing metadata. // // The only supported type now is *orca_v3.LoadReport. - ServerLoad interface{} + ServerLoad any } var ( @@ -414,15 +414,14 @@ var ErrBadResolverState = errors.New("bad resolver state") type ProducerBuilder interface { // Build creates a Producer. The first parameter is always a // grpc.ClientConnInterface (a type to allow creating RPCs/streams on the - // associated SubConn), but is declared as interface{} to avoid a - // dependency cycle. Should also return a close function that will be - // called when all references to the Producer have been given up. - Build(grpcClientConnInterface interface{}) (p Producer, close func()) + // associated SubConn), but is declared as `any` to avoid a dependency + // cycle. Should also return a close function that will be called when all + // references to the Producer have been given up. + Build(grpcClientConnInterface any) (p Producer, close func()) } // A Producer is a type shared among potentially many consumers. It is // associated with a SubConn, and an implementation will typically contain // other methods to provide additional functionality, e.g. configuration or // subscription registration. -type Producer interface { -} +type Producer any diff --git a/balancer/rls/control_channel_test.go b/balancer/rls/control_channel_test.go index d401d4cb6de8..dc7acd32c863 100644 --- a/balancer/rls/control_channel_test.go +++ b/balancer/rls/control_channel_test.go @@ -109,7 +109,7 @@ func (s) TestLookupFailure(t *testing.T) { // respond within the configured rpc timeout. func (s) TestLookupDeadlineExceeded(t *testing.T) { // A unary interceptor which returns a status error with DeadlineExceeded. - interceptor := func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + interceptor := func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { return nil, status.Error(codes.DeadlineExceeded, "deadline exceeded") } @@ -191,7 +191,7 @@ func (f *testPerRPCCredentials) RequireTransportSecurity() bool { // Unary server interceptor which validates if the RPC contains call credentials // which match `perRPCCredsData -func callCredsValidatingServerInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { +func callCredsValidatingServerInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, status.Error(codes.PermissionDenied, "didn't find metadata in context") diff --git a/balancer/rls/picker_test.go b/balancer/rls/picker_test.go index a2f84b265b1f..c0970e809f7a 100644 --- a/balancer/rls/picker_test.go +++ b/balancer/rls/picker_test.go @@ -158,7 +158,7 @@ func (s) TestPick_DataCacheMiss_PendingEntryExists(t *testing.T) { // also lead to creation of a pending entry, and further RPCs by the // client should not result in RLS requests being sent out. rlsReqCh := make(chan struct{}, 1) - interceptor := func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + interceptor := func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { rlsReqCh <- struct{}{} <-ctx.Done() return nil, ctx.Err() @@ -633,7 +633,7 @@ func (s) TestPick_DataCacheHit_PendingEntryExists_StaleEntry(t *testing.T) { // expired entry and a pending entry in the cache. rlsReqCh := make(chan struct{}, 1) firstRPCDone := grpcsync.NewEvent() - interceptor := func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + interceptor := func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { select { case rlsReqCh <- struct{}{}: default: @@ -733,7 +733,7 @@ func (s) TestPick_DataCacheHit_PendingEntryExists_ExpiredEntry(t *testing.T) { // expired entry and a pending entry in the cache. rlsReqCh := make(chan struct{}, 1) firstRPCDone := grpcsync.NewEvent() - interceptor := func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + interceptor := func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { select { case rlsReqCh <- struct{}{}: default: diff --git a/balancer/weightedroundrobin/weightedroundrobin.go b/balancer/weightedroundrobin/weightedroundrobin.go index 7567462e023d..8741fdad19dc 100644 --- a/balancer/weightedroundrobin/weightedroundrobin.go +++ b/balancer/weightedroundrobin/weightedroundrobin.go @@ -44,7 +44,7 @@ type AddrInfo struct { } // Equal allows the values to be compared by Attributes.Equal. -func (a AddrInfo) Equal(o interface{}) bool { +func (a AddrInfo) Equal(o any) bool { oa, ok := o.(AddrInfo) return ok && oa.Weight == a.Weight } diff --git a/balancer_conn_wrappers.go b/balancer_conn_wrappers.go index 5aaf00eaa7bd..a4411c22bfc8 100644 --- a/balancer_conn_wrappers.go +++ b/balancer_conn_wrappers.go @@ -406,7 +406,7 @@ func (acbw *acBalancerWrapper) NewStream(ctx context.Context, desc *StreamDesc, // Invoke performs a unary RPC. If the addrConn is not ready, returns // errSubConnNotReady. -func (acbw *acBalancerWrapper) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error { +func (acbw *acBalancerWrapper) Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error { cs, err := acbw.NewStream(ctx, unaryStreamDesc, method, opts...) if err != nil { return err diff --git a/benchmark/benchmain/main.go b/benchmark/benchmain/main.go index 76c1a265e50f..ec26909ba79d 100644 --- a/benchmark/benchmain/main.go +++ b/benchmark/benchmain/main.go @@ -425,7 +425,7 @@ func makeFuncStream(bf stats.Features) (rpcCallFunc, rpcCleanupFunc) { if bf.RespPayloadCurve != nil { respSizeBytes = bf.RespPayloadCurve.ChooseRandom() } - var req interface{} + var req any if bf.EnablePreloader { req = preparedMsg[cn][pos] } else { @@ -519,7 +519,7 @@ func unaryCaller(client testgrpc.BenchmarkServiceClient, reqSize, respSize int) } } -func streamCaller(stream testgrpc.BenchmarkService_StreamingCallClient, req interface{}) { +func streamCaller(stream testgrpc.BenchmarkService_StreamingCallClient, req any) { if err := bm.DoStreamingRoundTripPreloaded(stream, req); err != nil { logger.Fatalf("DoStreamingRoundTrip failed: %v", err) } diff --git a/benchmark/benchmark.go b/benchmark/benchmark.go index 27101954aa30..df2d2126439b 100644 --- a/benchmark/benchmark.go +++ b/benchmark/benchmark.go @@ -248,7 +248,7 @@ type ServerInfo struct { // Metadata is an optional configuration. // For "protobuf", it's ignored. // For "bytebuf", it should be an int representing response size. - Metadata interface{} + Metadata any // Listener is the network listener for the server to use Listener net.Listener @@ -302,7 +302,7 @@ func DoStreamingRoundTrip(stream testgrpc.BenchmarkService_StreamingCallClient, } // DoStreamingRoundTripPreloaded performs a round trip for a single streaming rpc with preloaded payload. -func DoStreamingRoundTripPreloaded(stream testgrpc.BenchmarkService_StreamingCallClient, req interface{}) error { +func DoStreamingRoundTripPreloaded(stream testgrpc.BenchmarkService_StreamingCallClient, req any) error { // req could be either *testpb.SimpleRequest or *grpc.PreparedMsg if err := stream.SendMsg(req); err != nil { return fmt.Errorf("/BenchmarkService/StreamingCall.Send(_) = %v, want ", err) diff --git a/benchmark/primitives/primitives_test.go b/benchmark/primitives/primitives_test.go index 8272f2d4afe0..dbbb313e8dcc 100644 --- a/benchmark/primitives/primitives_test.go +++ b/benchmark/primitives/primitives_test.go @@ -367,7 +367,7 @@ func BenchmarkInterfaceTypeAssertion(b *testing.B) { runInterfaceTypeAssertion(b, myFooer{}) } -func runInterfaceTypeAssertion(b *testing.B, fer interface{}) { +func runInterfaceTypeAssertion(b *testing.B, fer any) { x := 0 b.ResetTimer() for i := 0; i < b.N; i++ { @@ -386,7 +386,7 @@ func BenchmarkStructTypeAssertion(b *testing.B) { runStructTypeAssertion(b, myFooer{}) } -func runStructTypeAssertion(b *testing.B, fer interface{}) { +func runStructTypeAssertion(b *testing.B, fer any) { x := 0 b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/benchmark/worker/main.go b/benchmark/worker/main.go index 901341f51e7d..793fd76bcd40 100644 --- a/benchmark/worker/main.go +++ b/benchmark/worker/main.go @@ -53,7 +53,7 @@ var ( type byteBufCodec struct { } -func (byteBufCodec) Marshal(v interface{}) ([]byte, error) { +func (byteBufCodec) Marshal(v any) ([]byte, error) { b, ok := v.(*[]byte) if !ok { return nil, fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) @@ -61,7 +61,7 @@ func (byteBufCodec) Marshal(v interface{}) ([]byte, error) { return *b, nil } -func (byteBufCodec) Unmarshal(data []byte, v interface{}) error { +func (byteBufCodec) Unmarshal(data []byte, v any) error { b, ok := v.(*[]byte) if !ok { return fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) diff --git a/call.go b/call.go index e6a1dc5d75ed..7311d0126148 100644 --- a/call.go +++ b/call.go @@ -26,7 +26,7 @@ import ( // received. This is typically called by generated code. // // All errors returned by Invoke are compatible with the status package. -func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error { +func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply any, opts ...CallOption) error { if err := cc.idlenessMgr.onCallBegin(); err != nil { return err } @@ -61,13 +61,13 @@ func combine(o1 []CallOption, o2 []CallOption) []CallOption { // received. This is typically called by generated code. // // DEPRECATED: Use ClientConn.Invoke instead. -func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { +func Invoke(ctx context.Context, method string, args, reply any, cc *ClientConn, opts ...CallOption) error { return cc.Invoke(ctx, method, args, reply, opts...) } var unaryStreamDesc = &StreamDesc{ServerStreams: false, ClientStreams: false} -func invoke(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error { +func invoke(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error { cs, err := newClientStream(ctx, unaryStreamDesc, cc, method, opts...) if err != nil { return err diff --git a/clientconn.go b/clientconn.go index a226a1716bee..b0d28c67c7d4 100644 --- a/clientconn.go +++ b/clientconn.go @@ -492,7 +492,7 @@ func chainUnaryClientInterceptors(cc *ClientConn) { } else if len(interceptors) == 1 { chainedInt = interceptors[0] } else { - chainedInt = func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error { + chainedInt = func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error { return interceptors[0](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, 0, invoker), opts...) } } @@ -504,7 +504,7 @@ func getChainUnaryInvoker(interceptors []UnaryClientInterceptor, curr int, final if curr == len(interceptors)-1 { return finalInvoker } - return func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error { return interceptors[curr+1](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, curr+1, finalInvoker), opts...) } } @@ -607,7 +607,7 @@ func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} { type ClientConnInterface interface { // Invoke performs a unary RPC and returns after the response is received // into reply. - Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error + Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error // NewStream begins a streaming RPC. NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) } @@ -1581,7 +1581,7 @@ func (ac *addrConn) startHealthCheck(ctx context.Context) { // Set up the health check helper functions. currentTr := ac.transport - newStream := func(method string) (interface{}, error) { + newStream := func(method string) (any, error) { ac.mu.Lock() if ac.transport != currentTr { ac.mu.Unlock() diff --git a/cmd/protoc-gen-go-grpc/go.mod b/cmd/protoc-gen-go-grpc/go.mod index d24df99b88f6..92cf6c762689 100644 --- a/cmd/protoc-gen-go-grpc/go.mod +++ b/cmd/protoc-gen-go-grpc/go.mod @@ -1,5 +1,5 @@ module google.golang.org/grpc/cmd/protoc-gen-go-grpc -go 1.17 +go 1.19 require google.golang.org/protobuf v1.31.0 diff --git a/codec.go b/codec.go index 129776547811..411e3dfd47cc 100644 --- a/codec.go +++ b/codec.go @@ -27,8 +27,8 @@ import ( // omits the name/string, which vary between the two and are not needed for // anything besides the registry in the encoding package. type baseCodec interface { - Marshal(v interface{}) ([]byte, error) - Unmarshal(data []byte, v interface{}) error + Marshal(v any) ([]byte, error) + Unmarshal(data []byte, v any) error } var _ baseCodec = Codec(nil) @@ -41,9 +41,9 @@ var _ baseCodec = encoding.Codec(nil) // Deprecated: use encoding.Codec instead. type Codec interface { // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) + Marshal(v any) ([]byte, error) // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error + Unmarshal(data []byte, v any) error // String returns the name of the Codec implementation. This is unused by // gRPC. String() string diff --git a/credentials/tls/certprovider/pemfile/builder.go b/credentials/tls/certprovider/pemfile/builder.go index 957523caad10..8d8e2d4a0f5a 100644 --- a/credentials/tls/certprovider/pemfile/builder.go +++ b/credentials/tls/certprovider/pemfile/builder.go @@ -39,7 +39,7 @@ func init() { type pluginBuilder struct{} -func (p *pluginBuilder) ParseConfig(c interface{}) (*certprovider.BuildableConfig, error) { +func (p *pluginBuilder) ParseConfig(c any) (*certprovider.BuildableConfig, error) { data, ok := c.(json.RawMessage) if !ok { return nil, fmt.Errorf("meshca: unsupported config type: %T", c) diff --git a/credentials/tls/certprovider/pemfile/builder_test.go b/credentials/tls/certprovider/pemfile/builder_test.go index bef00e10c19d..dfd5ee899233 100644 --- a/credentials/tls/certprovider/pemfile/builder_test.go +++ b/credentials/tls/certprovider/pemfile/builder_test.go @@ -26,7 +26,7 @@ import ( func TestParseConfig(t *testing.T) { tests := []struct { desc string - input interface{} + input any wantOutput string wantErr bool }{ diff --git a/credentials/tls/certprovider/provider.go b/credentials/tls/certprovider/provider.go index f24df7c5008b..07ba05b10746 100644 --- a/credentials/tls/certprovider/provider.go +++ b/credentials/tls/certprovider/provider.go @@ -66,7 +66,7 @@ func getBuilder(name string) Builder { type Builder interface { // ParseConfig parses the given config, which is in a format specific to individual // implementations, and returns a BuildableConfig on success. - ParseConfig(interface{}) (*BuildableConfig, error) + ParseConfig(any) (*BuildableConfig, error) // Name returns the name of providers built by this builder. Name() string diff --git a/credentials/tls/certprovider/store.go b/credentials/tls/certprovider/store.go index 90f98b3c9e71..5c72f192cc33 100644 --- a/credentials/tls/certprovider/store.go +++ b/credentials/tls/certprovider/store.go @@ -31,8 +31,8 @@ var provStore = &store{ // storeKey acts as the key to the map of providers maintained by the store. A // combination of provider name and configuration is used to uniquely identify // every provider instance in the store. Go maps need to be indexed by -// comparable types, so the provider configuration is converted from -// `interface{}` to string using the ParseConfig method while creating this key. +// comparable types, so the provider configuration is converted from `any` to +// `string` using the ParseConfig method while creating this key. type storeKey struct { // name of the certificate provider. name string @@ -137,7 +137,7 @@ func (bc *BuildableConfig) String() string { // ParseConfig is a convenience function to create a BuildableConfig given a // provider name and configuration. Returns an error if there is no registered // builder for the given name or if the config parsing fails. -func ParseConfig(name string, config interface{}) (*BuildableConfig, error) { +func ParseConfig(name string, config any) (*BuildableConfig, error) { parser := getBuilder(name) if parser == nil { return nil, fmt.Errorf("no certificate provider builder found for %q", name) @@ -147,7 +147,7 @@ func ParseConfig(name string, config interface{}) (*BuildableConfig, error) { // GetProvider is a convenience function to create a provider given the name, // config and build options. -func GetProvider(name string, config interface{}, opts BuildOptions) (Provider, error) { +func GetProvider(name string, config any, opts BuildOptions) (Provider, error) { bc, err := ParseConfig(name, config) if err != nil { return nil, err diff --git a/credentials/tls/certprovider/store_test.go b/credentials/tls/certprovider/store_test.go index 54384e8225ef..dce61912977b 100644 --- a/credentials/tls/certprovider/store_test.go +++ b/credentials/tls/certprovider/store_test.go @@ -73,7 +73,7 @@ type fakeProviderBuilder struct { providerChan *testutils.Channel } -func (b *fakeProviderBuilder) ParseConfig(config interface{}) (*BuildableConfig, error) { +func (b *fakeProviderBuilder) ParseConfig(config any) (*BuildableConfig, error) { s, ok := config.(string) if !ok { return nil, fmt.Errorf("providerBuilder %s received config of type %T, want string", b.name, config) diff --git a/encoding/encoding.go b/encoding/encoding.go index 07a5861352a6..69d5580b6adf 100644 --- a/encoding/encoding.go +++ b/encoding/encoding.go @@ -90,9 +90,9 @@ func GetCompressor(name string) Compressor { // methods can be called from concurrent goroutines. type Codec interface { // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) + Marshal(v any) ([]byte, error) // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error + Unmarshal(data []byte, v any) error // Name returns the name of the Codec implementation. The returned string // will be used as part of content type in transmission. The result must be // static; the result cannot change between calls. diff --git a/encoding/gzip/gzip.go b/encoding/gzip/gzip.go index a3bb173c24ac..6306e8bb0f0a 100644 --- a/encoding/gzip/gzip.go +++ b/encoding/gzip/gzip.go @@ -40,7 +40,7 @@ const Name = "gzip" func init() { c := &compressor{} - c.poolCompressor.New = func() interface{} { + c.poolCompressor.New = func() any { return &writer{Writer: gzip.NewWriter(io.Discard), pool: &c.poolCompressor} } encoding.RegisterCompressor(c) @@ -61,7 +61,7 @@ func SetLevel(level int) error { return fmt.Errorf("grpc: invalid gzip compression level: %d", level) } c := encoding.GetCompressor(Name).(*compressor) - c.poolCompressor.New = func() interface{} { + c.poolCompressor.New = func() any { w, err := gzip.NewWriterLevel(io.Discard, level) if err != nil { panic(err) diff --git a/encoding/proto/proto.go b/encoding/proto/proto.go index 3009b35afe7d..0ee3d3bae973 100644 --- a/encoding/proto/proto.go +++ b/encoding/proto/proto.go @@ -37,7 +37,7 @@ func init() { // codec is a Codec implementation with protobuf. It is the default codec for gRPC. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { vv, ok := v.(proto.Message) if !ok { return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) @@ -45,7 +45,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) { return proto.Marshal(vv) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { vv, ok := v.(proto.Message) if !ok { return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) diff --git a/examples/features/authentication/server/main.go b/examples/features/authentication/server/main.go index 5163fc31671b..1b3b5e8ad202 100644 --- a/examples/features/authentication/server/main.go +++ b/examples/features/authentication/server/main.go @@ -97,7 +97,7 @@ func valid(authorization []string) bool { // the token is missing or invalid, the interceptor blocks execution of the // handler and returns an error. Otherwise, the interceptor invokes the unary // handler. -func ensureValidToken(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func ensureValidToken(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, errMissingMetadata diff --git a/examples/features/authz/server/main.go b/examples/features/authz/server/main.go index e06ddbdf153e..e66a5406de7b 100644 --- a/examples/features/authz/server/main.go +++ b/examples/features/authz/server/main.go @@ -140,7 +140,7 @@ func isAuthenticated(authorization []string) (username string, err error) { // authUnaryInterceptor looks up the authorization header from the incoming RPC context, // retrieves the username from it and creates a new context with the username before invoking // the provided handler. -func authUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func authUnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, errMissingMetadata @@ -171,7 +171,7 @@ func newWrappedStream(ctx context.Context, s grpc.ServerStream) grpc.ServerStrea // authStreamInterceptor looks up the authorization header from the incoming RPC context, // retrieves the username from it and creates a new context with the username before invoking // the provided handler. -func authStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func authStreamInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { md, ok := metadata.FromIncomingContext(ss.Context()) if !ok { return errMissingMetadata diff --git a/examples/features/interceptor/client/main.go b/examples/features/interceptor/client/main.go index 0832e4861cdd..4bfa9be29a75 100644 --- a/examples/features/interceptor/client/main.go +++ b/examples/features/interceptor/client/main.go @@ -40,12 +40,12 @@ var addr = flag.String("addr", "localhost:50051", "the address to connect to") const fallbackToken = "some-secret-token" // logger is to mock a sophisticated logging system. To simplify the example, we just print out the content. -func logger(format string, a ...interface{}) { +func logger(format string, a ...any) { fmt.Printf("LOG:\t"+format+"\n", a...) } // unaryInterceptor is an example unary interceptor. -func unaryInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { +func unaryInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { var credsConfigured bool for _, o := range opts { _, ok := o.(grpc.PerRPCCredsCallOption) @@ -72,12 +72,12 @@ type wrappedStream struct { grpc.ClientStream } -func (w *wrappedStream) RecvMsg(m interface{}) error { +func (w *wrappedStream) RecvMsg(m any) error { logger("Receive a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339)) return w.ClientStream.RecvMsg(m) } -func (w *wrappedStream) SendMsg(m interface{}) error { +func (w *wrappedStream) SendMsg(m any) error { logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339)) return w.ClientStream.SendMsg(m) } diff --git a/examples/features/interceptor/server/main.go b/examples/features/interceptor/server/main.go index 78b87aae3472..57d520acdbd3 100644 --- a/examples/features/interceptor/server/main.go +++ b/examples/features/interceptor/server/main.go @@ -47,7 +47,7 @@ var ( ) // logger is to mock a sophisticated logging system. To simplify the example, we just print out the content. -func logger(format string, a ...interface{}) { +func logger(format string, a ...any) { fmt.Printf("LOG:\t"+format+"\n", a...) } @@ -87,7 +87,7 @@ func valid(authorization []string) bool { return token == "some-secret-token" } -func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func unaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { // authentication (token verification) md, ok := metadata.FromIncomingContext(ctx) if !ok { @@ -109,12 +109,12 @@ type wrappedStream struct { grpc.ServerStream } -func (w *wrappedStream) RecvMsg(m interface{}) error { +func (w *wrappedStream) RecvMsg(m any) error { logger("Receive a message (Type: %T) at %s", m, time.Now().Format(time.RFC3339)) return w.ServerStream.RecvMsg(m) } -func (w *wrappedStream) SendMsg(m interface{}) error { +func (w *wrappedStream) SendMsg(m any) error { logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339)) return w.ServerStream.SendMsg(m) } @@ -123,7 +123,7 @@ func newWrappedStream(s grpc.ServerStream) grpc.ServerStream { return &wrappedStream{s} } -func streamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func streamInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { // authentication (token verification) md, ok := metadata.FromIncomingContext(ss.Context()) if !ok { diff --git a/examples/features/metadata_interceptor/server/main.go b/examples/features/metadata_interceptor/server/main.go index 8f0dc5bfe6d4..1d8f1d3262f8 100644 --- a/examples/features/metadata_interceptor/server/main.go +++ b/examples/features/metadata_interceptor/server/main.go @@ -43,7 +43,7 @@ type server struct { pb.UnimplementedEchoServer } -func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func unaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, errMissingMetadata @@ -83,7 +83,7 @@ func (s *wrappedStream) Context() context.Context { return s.ctx } -func streamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func streamInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { md, ok := metadata.FromIncomingContext(ss.Context()) if !ok { return errMissingMetadata diff --git a/examples/features/observability/go.mod b/examples/features/observability/go.mod index a7b3e2f8dc38..5d7f9ad53ac8 100644 --- a/examples/features/observability/go.mod +++ b/examples/features/observability/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/examples/features/observability -go 1.17 +go 1.19 require ( google.golang.org/grpc v1.54.0 diff --git a/examples/go.mod b/examples/go.mod index 17aef6d2e77a..e4b2103e0b34 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/examples -go 1.17 +go 1.19 require ( github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4 diff --git a/gcp/observability/go.mod b/gcp/observability/go.mod index 0413514ff478..a3d7ed89e12c 100644 --- a/gcp/observability/go.mod +++ b/gcp/observability/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/gcp/observability -go 1.17 +go 1.19 require ( cloud.google.com/go/logging v1.7.0 diff --git a/gcp/observability/opencensus.go b/gcp/observability/opencensus.go index abd3cb55b803..9b262e4ad278 100644 --- a/gcp/observability/opencensus.go +++ b/gcp/observability/opencensus.go @@ -60,8 +60,8 @@ func labelsToMonitoringLabels(labels map[string]string) *stackdriver.Labels { return sdLabels } -func labelsToTraceAttributes(labels map[string]string) map[string]interface{} { - ta := make(map[string]interface{}, len(labels)) +func labelsToTraceAttributes(labels map[string]string) map[string]any { + ta := make(map[string]any, len(labels)) for k, v := range labels { ta[k] = v } diff --git a/go.mod b/go.mod index 3352f5edef43..5e3bd51e4ac0 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc -go 1.17 +go 1.19 require ( github.com/cespare/xxhash/v2 v2.2.0 diff --git a/grpclog/component.go b/grpclog/component.go index 8358dd6e2abb..ac73c9ced255 100644 --- a/grpclog/component.go +++ b/grpclog/component.go @@ -31,71 +31,71 @@ type componentData struct { var cache = map[string]*componentData{} -func (c *componentData) InfoDepth(depth int, args ...interface{}) { - args = append([]interface{}{"[" + string(c.name) + "]"}, args...) +func (c *componentData) InfoDepth(depth int, args ...any) { + args = append([]any{"[" + string(c.name) + "]"}, args...) grpclog.InfoDepth(depth+1, args...) } -func (c *componentData) WarningDepth(depth int, args ...interface{}) { - args = append([]interface{}{"[" + string(c.name) + "]"}, args...) +func (c *componentData) WarningDepth(depth int, args ...any) { + args = append([]any{"[" + string(c.name) + "]"}, args...) grpclog.WarningDepth(depth+1, args...) } -func (c *componentData) ErrorDepth(depth int, args ...interface{}) { - args = append([]interface{}{"[" + string(c.name) + "]"}, args...) +func (c *componentData) ErrorDepth(depth int, args ...any) { + args = append([]any{"[" + string(c.name) + "]"}, args...) grpclog.ErrorDepth(depth+1, args...) } -func (c *componentData) FatalDepth(depth int, args ...interface{}) { - args = append([]interface{}{"[" + string(c.name) + "]"}, args...) +func (c *componentData) FatalDepth(depth int, args ...any) { + args = append([]any{"[" + string(c.name) + "]"}, args...) grpclog.FatalDepth(depth+1, args...) } -func (c *componentData) Info(args ...interface{}) { +func (c *componentData) Info(args ...any) { c.InfoDepth(1, args...) } -func (c *componentData) Warning(args ...interface{}) { +func (c *componentData) Warning(args ...any) { c.WarningDepth(1, args...) } -func (c *componentData) Error(args ...interface{}) { +func (c *componentData) Error(args ...any) { c.ErrorDepth(1, args...) } -func (c *componentData) Fatal(args ...interface{}) { +func (c *componentData) Fatal(args ...any) { c.FatalDepth(1, args...) } -func (c *componentData) Infof(format string, args ...interface{}) { +func (c *componentData) Infof(format string, args ...any) { c.InfoDepth(1, fmt.Sprintf(format, args...)) } -func (c *componentData) Warningf(format string, args ...interface{}) { +func (c *componentData) Warningf(format string, args ...any) { c.WarningDepth(1, fmt.Sprintf(format, args...)) } -func (c *componentData) Errorf(format string, args ...interface{}) { +func (c *componentData) Errorf(format string, args ...any) { c.ErrorDepth(1, fmt.Sprintf(format, args...)) } -func (c *componentData) Fatalf(format string, args ...interface{}) { +func (c *componentData) Fatalf(format string, args ...any) { c.FatalDepth(1, fmt.Sprintf(format, args...)) } -func (c *componentData) Infoln(args ...interface{}) { +func (c *componentData) Infoln(args ...any) { c.InfoDepth(1, args...) } -func (c *componentData) Warningln(args ...interface{}) { +func (c *componentData) Warningln(args ...any) { c.WarningDepth(1, args...) } -func (c *componentData) Errorln(args ...interface{}) { +func (c *componentData) Errorln(args ...any) { c.ErrorDepth(1, args...) } -func (c *componentData) Fatalln(args ...interface{}) { +func (c *componentData) Fatalln(args ...any) { c.FatalDepth(1, args...) } diff --git a/grpclog/glogger/glogger.go b/grpclog/glogger/glogger.go index 4427dc078bb4..fdabb602f55e 100644 --- a/grpclog/glogger/glogger.go +++ b/grpclog/glogger/glogger.go @@ -35,67 +35,67 @@ func init() { type glogger struct{} -func (g *glogger) Info(args ...interface{}) { +func (g *glogger) Info(args ...any) { glog.InfoDepth(d, args...) } -func (g *glogger) Infoln(args ...interface{}) { +func (g *glogger) Infoln(args ...any) { glog.InfoDepth(d, fmt.Sprintln(args...)) } -func (g *glogger) Infof(format string, args ...interface{}) { +func (g *glogger) Infof(format string, args ...any) { glog.InfoDepth(d, fmt.Sprintf(format, args...)) } -func (g *glogger) InfoDepth(depth int, args ...interface{}) { +func (g *glogger) InfoDepth(depth int, args ...any) { glog.InfoDepth(depth+d, args...) } -func (g *glogger) Warning(args ...interface{}) { +func (g *glogger) Warning(args ...any) { glog.WarningDepth(d, args...) } -func (g *glogger) Warningln(args ...interface{}) { +func (g *glogger) Warningln(args ...any) { glog.WarningDepth(d, fmt.Sprintln(args...)) } -func (g *glogger) Warningf(format string, args ...interface{}) { +func (g *glogger) Warningf(format string, args ...any) { glog.WarningDepth(d, fmt.Sprintf(format, args...)) } -func (g *glogger) WarningDepth(depth int, args ...interface{}) { +func (g *glogger) WarningDepth(depth int, args ...any) { glog.WarningDepth(depth+d, args...) } -func (g *glogger) Error(args ...interface{}) { +func (g *glogger) Error(args ...any) { glog.ErrorDepth(d, args...) } -func (g *glogger) Errorln(args ...interface{}) { +func (g *glogger) Errorln(args ...any) { glog.ErrorDepth(d, fmt.Sprintln(args...)) } -func (g *glogger) Errorf(format string, args ...interface{}) { +func (g *glogger) Errorf(format string, args ...any) { glog.ErrorDepth(d, fmt.Sprintf(format, args...)) } -func (g *glogger) ErrorDepth(depth int, args ...interface{}) { +func (g *glogger) ErrorDepth(depth int, args ...any) { glog.ErrorDepth(depth+d, args...) } -func (g *glogger) Fatal(args ...interface{}) { +func (g *glogger) Fatal(args ...any) { glog.FatalDepth(d, args...) } -func (g *glogger) Fatalln(args ...interface{}) { +func (g *glogger) Fatalln(args ...any) { glog.FatalDepth(d, fmt.Sprintln(args...)) } -func (g *glogger) Fatalf(format string, args ...interface{}) { +func (g *glogger) Fatalf(format string, args ...any) { glog.FatalDepth(d, fmt.Sprintf(format, args...)) } -func (g *glogger) FatalDepth(depth int, args ...interface{}) { +func (g *glogger) FatalDepth(depth int, args ...any) { glog.FatalDepth(depth+d, args...) } diff --git a/grpclog/grpclog.go b/grpclog/grpclog.go index c8bb2be34bf5..16928c9cb993 100644 --- a/grpclog/grpclog.go +++ b/grpclog/grpclog.go @@ -42,53 +42,53 @@ func V(l int) bool { } // Info logs to the INFO log. -func Info(args ...interface{}) { +func Info(args ...any) { grpclog.Logger.Info(args...) } // Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf. -func Infof(format string, args ...interface{}) { +func Infof(format string, args ...any) { grpclog.Logger.Infof(format, args...) } // Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println. -func Infoln(args ...interface{}) { +func Infoln(args ...any) { grpclog.Logger.Infoln(args...) } // Warning logs to the WARNING log. -func Warning(args ...interface{}) { +func Warning(args ...any) { grpclog.Logger.Warning(args...) } // Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf. -func Warningf(format string, args ...interface{}) { +func Warningf(format string, args ...any) { grpclog.Logger.Warningf(format, args...) } // Warningln logs to the WARNING log. Arguments are handled in the manner of fmt.Println. -func Warningln(args ...interface{}) { +func Warningln(args ...any) { grpclog.Logger.Warningln(args...) } // Error logs to the ERROR log. -func Error(args ...interface{}) { +func Error(args ...any) { grpclog.Logger.Error(args...) } // Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf. -func Errorf(format string, args ...interface{}) { +func Errorf(format string, args ...any) { grpclog.Logger.Errorf(format, args...) } // Errorln logs to the ERROR log. Arguments are handled in the manner of fmt.Println. -func Errorln(args ...interface{}) { +func Errorln(args ...any) { grpclog.Logger.Errorln(args...) } // Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Print. // It calls os.Exit() with exit code 1. -func Fatal(args ...interface{}) { +func Fatal(args ...any) { grpclog.Logger.Fatal(args...) // Make sure fatal logs will exit. os.Exit(1) @@ -96,7 +96,7 @@ func Fatal(args ...interface{}) { // Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf. // It calls os.Exit() with exit code 1. -func Fatalf(format string, args ...interface{}) { +func Fatalf(format string, args ...any) { grpclog.Logger.Fatalf(format, args...) // Make sure fatal logs will exit. os.Exit(1) @@ -104,7 +104,7 @@ func Fatalf(format string, args ...interface{}) { // Fatalln logs to the FATAL log. Arguments are handled in the manner of fmt.Println. // It calle os.Exit()) with exit code 1. -func Fatalln(args ...interface{}) { +func Fatalln(args ...any) { grpclog.Logger.Fatalln(args...) // Make sure fatal logs will exit. os.Exit(1) @@ -113,20 +113,20 @@ func Fatalln(args ...interface{}) { // Print prints to the logger. Arguments are handled in the manner of fmt.Print. // // Deprecated: use Info. -func Print(args ...interface{}) { +func Print(args ...any) { grpclog.Logger.Info(args...) } // Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. // // Deprecated: use Infof. -func Printf(format string, args ...interface{}) { +func Printf(format string, args ...any) { grpclog.Logger.Infof(format, args...) } // Println prints to the logger. Arguments are handled in the manner of fmt.Println. // // Deprecated: use Infoln. -func Println(args ...interface{}) { +func Println(args ...any) { grpclog.Logger.Infoln(args...) } diff --git a/grpclog/logger.go b/grpclog/logger.go index ef06a4822b70..b1674d8267ca 100644 --- a/grpclog/logger.go +++ b/grpclog/logger.go @@ -24,12 +24,12 @@ import "google.golang.org/grpc/internal/grpclog" // // Deprecated: use LoggerV2. type Logger interface { - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Fatalln(args ...interface{}) - Print(args ...interface{}) - Printf(format string, args ...interface{}) - Println(args ...interface{}) + Fatal(args ...any) + Fatalf(format string, args ...any) + Fatalln(args ...any) + Print(args ...any) + Printf(format string, args ...any) + Println(args ...any) } // SetLogger sets the logger that is used in grpc. Call only from @@ -45,39 +45,39 @@ type loggerWrapper struct { Logger } -func (g *loggerWrapper) Info(args ...interface{}) { +func (g *loggerWrapper) Info(args ...any) { g.Logger.Print(args...) } -func (g *loggerWrapper) Infoln(args ...interface{}) { +func (g *loggerWrapper) Infoln(args ...any) { g.Logger.Println(args...) } -func (g *loggerWrapper) Infof(format string, args ...interface{}) { +func (g *loggerWrapper) Infof(format string, args ...any) { g.Logger.Printf(format, args...) } -func (g *loggerWrapper) Warning(args ...interface{}) { +func (g *loggerWrapper) Warning(args ...any) { g.Logger.Print(args...) } -func (g *loggerWrapper) Warningln(args ...interface{}) { +func (g *loggerWrapper) Warningln(args ...any) { g.Logger.Println(args...) } -func (g *loggerWrapper) Warningf(format string, args ...interface{}) { +func (g *loggerWrapper) Warningf(format string, args ...any) { g.Logger.Printf(format, args...) } -func (g *loggerWrapper) Error(args ...interface{}) { +func (g *loggerWrapper) Error(args ...any) { g.Logger.Print(args...) } -func (g *loggerWrapper) Errorln(args ...interface{}) { +func (g *loggerWrapper) Errorln(args ...any) { g.Logger.Println(args...) } -func (g *loggerWrapper) Errorf(format string, args ...interface{}) { +func (g *loggerWrapper) Errorf(format string, args ...any) { g.Logger.Printf(format, args...) } diff --git a/grpclog/loggerv2.go b/grpclog/loggerv2.go index 5de66e40d365..ecfd36d71303 100644 --- a/grpclog/loggerv2.go +++ b/grpclog/loggerv2.go @@ -33,35 +33,35 @@ import ( // LoggerV2 does underlying logging work for grpclog. type LoggerV2 interface { // Info logs to INFO log. Arguments are handled in the manner of fmt.Print. - Info(args ...interface{}) + Info(args ...any) // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. - Infoln(args ...interface{}) + Infoln(args ...any) // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. - Infof(format string, args ...interface{}) + Infof(format string, args ...any) // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print. - Warning(args ...interface{}) + Warning(args ...any) // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. - Warningln(args ...interface{}) + Warningln(args ...any) // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. - Warningf(format string, args ...interface{}) + Warningf(format string, args ...any) // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print. - Error(args ...interface{}) + Error(args ...any) // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - Errorln(args ...interface{}) + Errorln(args ...any) // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - Errorf(format string, args ...interface{}) + Errorf(format string, args ...any) // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatal(args ...interface{}) + Fatal(args ...any) // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatalln(args ...interface{}) + Fatalln(args ...any) // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatalf(format string, args ...interface{}) + Fatalf(format string, args ...any) // V reports whether verbosity level l is at least the requested verbose level. V(l int) bool } @@ -182,53 +182,53 @@ func (g *loggerT) output(severity int, s string) { g.m[severity].Output(2, string(b)) } -func (g *loggerT) Info(args ...interface{}) { +func (g *loggerT) Info(args ...any) { g.output(infoLog, fmt.Sprint(args...)) } -func (g *loggerT) Infoln(args ...interface{}) { +func (g *loggerT) Infoln(args ...any) { g.output(infoLog, fmt.Sprintln(args...)) } -func (g *loggerT) Infof(format string, args ...interface{}) { +func (g *loggerT) Infof(format string, args ...any) { g.output(infoLog, fmt.Sprintf(format, args...)) } -func (g *loggerT) Warning(args ...interface{}) { +func (g *loggerT) Warning(args ...any) { g.output(warningLog, fmt.Sprint(args...)) } -func (g *loggerT) Warningln(args ...interface{}) { +func (g *loggerT) Warningln(args ...any) { g.output(warningLog, fmt.Sprintln(args...)) } -func (g *loggerT) Warningf(format string, args ...interface{}) { +func (g *loggerT) Warningf(format string, args ...any) { g.output(warningLog, fmt.Sprintf(format, args...)) } -func (g *loggerT) Error(args ...interface{}) { +func (g *loggerT) Error(args ...any) { g.output(errorLog, fmt.Sprint(args...)) } -func (g *loggerT) Errorln(args ...interface{}) { +func (g *loggerT) Errorln(args ...any) { g.output(errorLog, fmt.Sprintln(args...)) } -func (g *loggerT) Errorf(format string, args ...interface{}) { +func (g *loggerT) Errorf(format string, args ...any) { g.output(errorLog, fmt.Sprintf(format, args...)) } -func (g *loggerT) Fatal(args ...interface{}) { +func (g *loggerT) Fatal(args ...any) { g.output(fatalLog, fmt.Sprint(args...)) os.Exit(1) } -func (g *loggerT) Fatalln(args ...interface{}) { +func (g *loggerT) Fatalln(args ...any) { g.output(fatalLog, fmt.Sprintln(args...)) os.Exit(1) } -func (g *loggerT) Fatalf(format string, args ...interface{}) { +func (g *loggerT) Fatalf(format string, args ...any) { g.output(fatalLog, fmt.Sprintf(format, args...)) os.Exit(1) } @@ -248,11 +248,11 @@ func (g *loggerT) V(l int) bool { type DepthLoggerV2 interface { LoggerV2 // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Println. - InfoDepth(depth int, args ...interface{}) + InfoDepth(depth int, args ...any) // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Println. - WarningDepth(depth int, args ...interface{}) + WarningDepth(depth int, args ...any) // ErrorDepth logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Println. - ErrorDepth(depth int, args ...interface{}) + ErrorDepth(depth int, args ...any) // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Println. - FatalDepth(depth int, args ...interface{}) + FatalDepth(depth int, args ...any) } diff --git a/health/client.go b/health/client.go index b5bee4838024..740745c45f63 100644 --- a/health/client.go +++ b/health/client.go @@ -56,7 +56,7 @@ const healthCheckMethod = "/grpc.health.v1.Health/Watch" // This function implements the protocol defined at: // https://github.com/grpc/grpc/blob/master/doc/health-checking.md -func clientHealthCheck(ctx context.Context, newStream func(string) (interface{}, error), setConnectivityState func(connectivity.State, error), service string) error { +func clientHealthCheck(ctx context.Context, newStream func(string) (any, error), setConnectivityState func(connectivity.State, error), service string) error { tryCnt := 0 retryConnection: diff --git a/health/client_test.go b/health/client_test.go index ba933f95b84f..cc11bd212ba3 100644 --- a/health/client_test.go +++ b/health/client_test.go @@ -39,7 +39,7 @@ func (s) TestClientHealthCheckBackoff(t *testing.T) { } var got []time.Duration - newStream := func(string) (interface{}, error) { + newStream := func(string) (any, error) { if len(got) < maxRetries { return nil, errors.New("backoff") } diff --git a/interceptor.go b/interceptor.go index bb96ef57be89..877d78fc3d00 100644 --- a/interceptor.go +++ b/interceptor.go @@ -23,7 +23,7 @@ import ( ) // UnaryInvoker is called by UnaryClientInterceptor to complete RPCs. -type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error +type UnaryInvoker func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error // UnaryClientInterceptor intercepts the execution of a unary RPC on the client. // Unary interceptors can be specified as a DialOption, using @@ -40,7 +40,7 @@ type UnaryInvoker func(ctx context.Context, method string, req, reply interface{ // defaults from the ClientConn as well as per-call options. // // The returned error must be compatible with the status package. -type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error +type UnaryClientInterceptor func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error // Streamer is called by StreamClientInterceptor to create a ClientStream. type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) @@ -66,7 +66,7 @@ type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *Cli // server side. All per-rpc information may be mutated by the interceptor. type UnaryServerInfo struct { // Server is the service implementation the user provides. This is read-only. - Server interface{} + Server any // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string } @@ -78,13 +78,13 @@ type UnaryServerInfo struct { // status package, or be one of the context errors. Otherwise, gRPC will use // codes.Unknown as the status code and err.Error() as the status message of the // RPC. -type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) +type UnaryHandler func(ctx context.Context, req any) (any, error) // UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info // contains all the information of this RPC the interceptor can operate on. And handler is the wrapper // of the service method implementation. It is the responsibility of the interceptor to invoke handler // to complete the RPC. -type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) +type UnaryServerInterceptor func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) // StreamServerInfo consists of various information about a streaming RPC on // server side. All per-rpc information may be mutated by the interceptor. @@ -101,4 +101,4 @@ type StreamServerInfo struct { // info contains all the information of this RPC the interceptor can operate on. And handler is the // service method implementation. It is the responsibility of the interceptor to invoke handler to // complete the RPC. -type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error +type StreamServerInterceptor func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error diff --git a/internal/balancer/stub/stub.go b/internal/balancer/stub/stub.go index 9bae3d333666..71e3cb619d9c 100644 --- a/internal/balancer/stub/stub.go +++ b/internal/balancer/stub/stub.go @@ -50,7 +50,7 @@ type BalancerData struct { // BuildOptions is set by the builder. BuildOptions balancer.BuildOptions // Data may be used to store arbitrary user data. - Data interface{} + Data any } type bal struct { diff --git a/internal/balancerload/load.go b/internal/balancerload/load.go index 3a905d96657e..94a08d6875a9 100644 --- a/internal/balancerload/load.go +++ b/internal/balancerload/load.go @@ -25,7 +25,7 @@ import ( // Parser converts loads from metadata into a concrete type. type Parser interface { // Parse parses loads from metadata. - Parse(md metadata.MD) interface{} + Parse(md metadata.MD) any } var parser Parser @@ -38,7 +38,7 @@ func SetParser(lr Parser) { } // Parse calls parser.Read(). -func Parse(md metadata.MD) interface{} { +func Parse(md metadata.MD) any { if parser == nil { return nil } diff --git a/internal/binarylog/method_logger.go b/internal/binarylog/method_logger.go index 6c3f632215fd..0f31274a3ccc 100644 --- a/internal/binarylog/method_logger.go +++ b/internal/binarylog/method_logger.go @@ -230,7 +230,7 @@ type ClientMessage struct { OnClientSide bool // Message can be a proto.Message or []byte. Other messages formats are not // supported. - Message interface{} + Message any } func (c *ClientMessage) toProto() *binlogpb.GrpcLogEntry { @@ -270,7 +270,7 @@ type ServerMessage struct { OnClientSide bool // Message can be a proto.Message or []byte. Other messages formats are not // supported. - Message interface{} + Message any } func (c *ServerMessage) toProto() *binlogpb.GrpcLogEntry { diff --git a/internal/buffer/unbounded.go b/internal/buffer/unbounded.go index 81c2f5fd761b..4399c3df4959 100644 --- a/internal/buffer/unbounded.go +++ b/internal/buffer/unbounded.go @@ -28,25 +28,25 @@ import "sync" // the underlying mutex used for synchronization. // // Unbounded supports values of any type to be stored in it by using a channel -// of `interface{}`. This means that a call to Put() incurs an extra memory -// allocation, and also that users need a type assertion while reading. For -// performance critical code paths, using Unbounded is strongly discouraged and -// defining a new type specific implementation of this buffer is preferred. See +// of `any`. This means that a call to Put() incurs an extra memory allocation, +// and also that users need a type assertion while reading. For performance +// critical code paths, using Unbounded is strongly discouraged and defining a +// new type specific implementation of this buffer is preferred. See // internal/transport/transport.go for an example of this. type Unbounded struct { - c chan interface{} + c chan any closed bool mu sync.Mutex - backlog []interface{} + backlog []any } // NewUnbounded returns a new instance of Unbounded. func NewUnbounded() *Unbounded { - return &Unbounded{c: make(chan interface{}, 1)} + return &Unbounded{c: make(chan any, 1)} } // Put adds t to the unbounded buffer. -func (b *Unbounded) Put(t interface{}) { +func (b *Unbounded) Put(t any) { b.mu.Lock() defer b.mu.Unlock() if b.closed { @@ -89,7 +89,7 @@ func (b *Unbounded) Load() { // // If the unbounded buffer is closed, the read channel returned by this method // is closed. -func (b *Unbounded) Get() <-chan interface{} { +func (b *Unbounded) Get() <-chan any { return b.c } diff --git a/internal/cache/timeoutCache.go b/internal/cache/timeoutCache.go index 200b499ec81e..3f2d47302c4e 100644 --- a/internal/cache/timeoutCache.go +++ b/internal/cache/timeoutCache.go @@ -23,7 +23,7 @@ import ( ) type cacheEntry struct { - item interface{} + item any // Note that to avoid deadlocks (potentially caused by lock ordering), // callback can only be called without holding cache's mutex. callback func() @@ -38,14 +38,14 @@ type cacheEntry struct { type TimeoutCache struct { mu sync.Mutex timeout time.Duration - cache map[interface{}]*cacheEntry + cache map[any]*cacheEntry } // NewTimeoutCache creates a TimeoutCache with the given timeout. func NewTimeoutCache(timeout time.Duration) *TimeoutCache { return &TimeoutCache{ timeout: timeout, - cache: make(map[interface{}]*cacheEntry), + cache: make(map[any]*cacheEntry), } } @@ -57,7 +57,7 @@ func NewTimeoutCache(timeout time.Duration) *TimeoutCache { // If the Add was successful, it returns (newly added item, true). If there is // an existing entry for the specified key, the cache entry is not be updated // with the specified item and it returns (existing item, false). -func (c *TimeoutCache) Add(key, item interface{}, callback func()) (interface{}, bool) { +func (c *TimeoutCache) Add(key, item any, callback func()) (any, bool) { c.mu.Lock() defer c.mu.Unlock() if e, ok := c.cache[key]; ok { @@ -88,7 +88,7 @@ func (c *TimeoutCache) Add(key, item interface{}, callback func()) (interface{}, // If the specified key exists in the cache, it returns (item associated with // key, true) and the callback associated with the item is guaranteed to be not // called. If the given key is not found in the cache, it returns (nil, false) -func (c *TimeoutCache) Remove(key interface{}) (item interface{}, ok bool) { +func (c *TimeoutCache) Remove(key any) (item any, ok bool) { c.mu.Lock() defer c.mu.Unlock() entry, ok := c.removeInternal(key) @@ -101,7 +101,7 @@ func (c *TimeoutCache) Remove(key interface{}) (item interface{}, ok bool) { // removeInternal removes and returns the item with key. // // caller must hold c.mu. -func (c *TimeoutCache) removeInternal(key interface{}) (*cacheEntry, bool) { +func (c *TimeoutCache) removeInternal(key any) (*cacheEntry, bool) { entry, ok := c.cache[key] if !ok { return nil, false diff --git a/internal/cache/timeoutCache_test.go b/internal/cache/timeoutCache_test.go index 9129f47e72f1..106ea7c911d7 100644 --- a/internal/cache/timeoutCache_test.go +++ b/internal/cache/timeoutCache_test.go @@ -38,7 +38,7 @@ func Test(t *testing.T) { grpctest.RunSubTests(t, s{}) } -func (c *TimeoutCache) getForTesting(key interface{}) (*cacheEntry, bool) { +func (c *TimeoutCache) getForTesting(key any) (*cacheEntry, bool) { c.mu.Lock() defer c.mu.Unlock() r, ok := c.cache[key] diff --git a/internal/channelz/logging.go b/internal/channelz/logging.go index 8e13a3d2ce7b..f89e6f77bbd0 100644 --- a/internal/channelz/logging.go +++ b/internal/channelz/logging.go @@ -31,7 +31,7 @@ func withParens(id *Identifier) string { } // Info logs and adds a trace event if channelz is on. -func Info(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { +func Info(l grpclog.DepthLoggerV2, id *Identifier, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprint(args...), Severity: CtInfo, @@ -39,7 +39,7 @@ func Info(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { } // Infof logs and adds a trace event if channelz is on. -func Infof(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { +func Infof(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprintf(format, args...), Severity: CtInfo, @@ -47,7 +47,7 @@ func Infof(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...inter } // Warning logs and adds a trace event if channelz is on. -func Warning(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { +func Warning(l grpclog.DepthLoggerV2, id *Identifier, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprint(args...), Severity: CtWarning, @@ -55,7 +55,7 @@ func Warning(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { } // Warningf logs and adds a trace event if channelz is on. -func Warningf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { +func Warningf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprintf(format, args...), Severity: CtWarning, @@ -63,7 +63,7 @@ func Warningf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...in } // Error logs and adds a trace event if channelz is on. -func Error(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { +func Error(l grpclog.DepthLoggerV2, id *Identifier, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprint(args...), Severity: CtError, @@ -71,7 +71,7 @@ func Error(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { } // Errorf logs and adds a trace event if channelz is on. -func Errorf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { +func Errorf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...any) { AddTraceEvent(l, id, 1, &TraceEventDesc{ Desc: fmt.Sprintf(format, args...), Severity: CtError, diff --git a/internal/channelz/util_linux.go b/internal/channelz/util_linux.go index 8d194e44e1dc..98288c3f866f 100644 --- a/internal/channelz/util_linux.go +++ b/internal/channelz/util_linux.go @@ -23,7 +23,7 @@ import ( ) // GetSocketOption gets the socket option info of the conn. -func GetSocketOption(socket interface{}) *SocketOptionData { +func GetSocketOption(socket any) *SocketOptionData { c, ok := socket.(syscall.Conn) if !ok { return nil diff --git a/internal/channelz/util_nonlinux.go b/internal/channelz/util_nonlinux.go index 837ddc402400..b5568b22e208 100644 --- a/internal/channelz/util_nonlinux.go +++ b/internal/channelz/util_nonlinux.go @@ -22,6 +22,6 @@ package channelz // GetSocketOption gets the socket option info of the conn. -func GetSocketOption(c interface{}) *SocketOptionData { +func GetSocketOption(c any) *SocketOptionData { return nil } diff --git a/internal/credentials/credentials.go b/internal/credentials/credentials.go index 32c9b59033cd..9deee7f6513e 100644 --- a/internal/credentials/credentials.go +++ b/internal/credentials/credentials.go @@ -25,12 +25,12 @@ import ( type requestInfoKey struct{} // NewRequestInfoContext creates a context with ri. -func NewRequestInfoContext(ctx context.Context, ri interface{}) context.Context { +func NewRequestInfoContext(ctx context.Context, ri any) context.Context { return context.WithValue(ctx, requestInfoKey{}, ri) } // RequestInfoFromContext extracts the RequestInfo from ctx. -func RequestInfoFromContext(ctx context.Context) interface{} { +func RequestInfoFromContext(ctx context.Context) any { return ctx.Value(requestInfoKey{}) } @@ -39,11 +39,11 @@ func RequestInfoFromContext(ctx context.Context) interface{} { type clientHandshakeInfoKey struct{} // ClientHandshakeInfoFromContext extracts the ClientHandshakeInfo from ctx. -func ClientHandshakeInfoFromContext(ctx context.Context) interface{} { +func ClientHandshakeInfoFromContext(ctx context.Context) any { return ctx.Value(clientHandshakeInfoKey{}) } // NewClientHandshakeInfoContext creates a context with chi. -func NewClientHandshakeInfoContext(ctx context.Context, chi interface{}) context.Context { +func NewClientHandshakeInfoContext(ctx context.Context, chi any) context.Context { return context.WithValue(ctx, clientHandshakeInfoKey{}, chi) } diff --git a/internal/credentials/xds/handshake_info.go b/internal/credentials/xds/handshake_info.go index 9fa0c94f41e8..56970e0510bd 100644 --- a/internal/credentials/xds/handshake_info.go +++ b/internal/credentials/xds/handshake_info.go @@ -46,7 +46,7 @@ type handshakeAttrKey struct{} // Equal reports whether the handshake info structs are identical (have the // same pointer). This is sufficient as all subconns from one CDS balancer use // the same one. -func (hi *HandshakeInfo) Equal(o interface{}) bool { +func (hi *HandshakeInfo) Equal(o any) bool { oh, ok := o.(*HandshakeInfo) return ok && oh == hi } diff --git a/internal/grpclog/grpclog.go b/internal/grpclog/grpclog.go index b68e26a36493..bfc45102ab24 100644 --- a/internal/grpclog/grpclog.go +++ b/internal/grpclog/grpclog.go @@ -30,7 +30,7 @@ var Logger LoggerV2 var DepthLogger DepthLoggerV2 // InfoDepth logs to the INFO log at the specified depth. -func InfoDepth(depth int, args ...interface{}) { +func InfoDepth(depth int, args ...any) { if DepthLogger != nil { DepthLogger.InfoDepth(depth, args...) } else { @@ -39,7 +39,7 @@ func InfoDepth(depth int, args ...interface{}) { } // WarningDepth logs to the WARNING log at the specified depth. -func WarningDepth(depth int, args ...interface{}) { +func WarningDepth(depth int, args ...any) { if DepthLogger != nil { DepthLogger.WarningDepth(depth, args...) } else { @@ -48,7 +48,7 @@ func WarningDepth(depth int, args ...interface{}) { } // ErrorDepth logs to the ERROR log at the specified depth. -func ErrorDepth(depth int, args ...interface{}) { +func ErrorDepth(depth int, args ...any) { if DepthLogger != nil { DepthLogger.ErrorDepth(depth, args...) } else { @@ -57,7 +57,7 @@ func ErrorDepth(depth int, args ...interface{}) { } // FatalDepth logs to the FATAL log at the specified depth. -func FatalDepth(depth int, args ...interface{}) { +func FatalDepth(depth int, args ...any) { if DepthLogger != nil { DepthLogger.FatalDepth(depth, args...) } else { @@ -71,35 +71,35 @@ func FatalDepth(depth int, args ...interface{}) { // is defined here to avoid a circular dependency. type LoggerV2 interface { // Info logs to INFO log. Arguments are handled in the manner of fmt.Print. - Info(args ...interface{}) + Info(args ...any) // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. - Infoln(args ...interface{}) + Infoln(args ...any) // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. - Infof(format string, args ...interface{}) + Infof(format string, args ...any) // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print. - Warning(args ...interface{}) + Warning(args ...any) // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. - Warningln(args ...interface{}) + Warningln(args ...any) // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. - Warningf(format string, args ...interface{}) + Warningf(format string, args ...any) // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print. - Error(args ...interface{}) + Error(args ...any) // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - Errorln(args ...interface{}) + Errorln(args ...any) // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - Errorf(format string, args ...interface{}) + Errorf(format string, args ...any) // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatal(args ...interface{}) + Fatal(args ...any) // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatalln(args ...interface{}) + Fatalln(args ...any) // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. - Fatalf(format string, args ...interface{}) + Fatalf(format string, args ...any) // V reports whether verbosity level l is at least the requested verbose level. V(l int) bool } @@ -116,11 +116,11 @@ type LoggerV2 interface { // later release. type DepthLoggerV2 interface { // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Println. - InfoDepth(depth int, args ...interface{}) + InfoDepth(depth int, args ...any) // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Println. - WarningDepth(depth int, args ...interface{}) + WarningDepth(depth int, args ...any) // ErrorDepth logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Println. - ErrorDepth(depth int, args ...interface{}) + ErrorDepth(depth int, args ...any) // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Println. - FatalDepth(depth int, args ...interface{}) + FatalDepth(depth int, args ...any) } diff --git a/internal/grpclog/prefixLogger.go b/internal/grpclog/prefixLogger.go index 02224b42ca86..faa998de7632 100644 --- a/internal/grpclog/prefixLogger.go +++ b/internal/grpclog/prefixLogger.go @@ -31,7 +31,7 @@ type PrefixLogger struct { } // Infof does info logging. -func (pl *PrefixLogger) Infof(format string, args ...interface{}) { +func (pl *PrefixLogger) Infof(format string, args ...any) { if pl != nil { // Handle nil, so the tests can pass in a nil logger. format = pl.prefix + format @@ -42,7 +42,7 @@ func (pl *PrefixLogger) Infof(format string, args ...interface{}) { } // Warningf does warning logging. -func (pl *PrefixLogger) Warningf(format string, args ...interface{}) { +func (pl *PrefixLogger) Warningf(format string, args ...any) { if pl != nil { format = pl.prefix + format pl.logger.WarningDepth(1, fmt.Sprintf(format, args...)) @@ -52,7 +52,7 @@ func (pl *PrefixLogger) Warningf(format string, args ...interface{}) { } // Errorf does error logging. -func (pl *PrefixLogger) Errorf(format string, args ...interface{}) { +func (pl *PrefixLogger) Errorf(format string, args ...any) { if pl != nil { format = pl.prefix + format pl.logger.ErrorDepth(1, fmt.Sprintf(format, args...)) @@ -62,7 +62,7 @@ func (pl *PrefixLogger) Errorf(format string, args ...interface{}) { } // Debugf does info logging at verbose level 2. -func (pl *PrefixLogger) Debugf(format string, args ...interface{}) { +func (pl *PrefixLogger) Debugf(format string, args ...any) { // TODO(6044): Refactor interfaces LoggerV2 and DepthLogger, and maybe // rewrite PrefixLogger a little to ensure that we don't use the global // `Logger` here, and instead use the `logger` field. diff --git a/internal/grpcsync/pubsub.go b/internal/grpcsync/pubsub.go index fdadca6b2737..aef8cec1ab0c 100644 --- a/internal/grpcsync/pubsub.go +++ b/internal/grpcsync/pubsub.go @@ -29,7 +29,7 @@ import ( type Subscriber interface { // OnMessage is invoked when a new message is published. Implementations // must not block in this method. - OnMessage(msg interface{}) + OnMessage(msg any) } // PubSub is a simple one-to-many publish-subscribe system that supports @@ -48,7 +48,7 @@ type PubSub struct { // Access to the below fields are guarded by this mutex. mu sync.Mutex - msg interface{} + msg any subscribers map[Subscriber]bool } @@ -96,7 +96,7 @@ func (ps *PubSub) Subscribe(sub Subscriber) (cancel func()) { // Publish publishes the provided message to the PubSub, and invokes // callbacks registered by subscribers asynchronously. -func (ps *PubSub) Publish(msg interface{}) { +func (ps *PubSub) Publish(msg any) { ps.mu.Lock() defer ps.mu.Unlock() diff --git a/internal/grpcsync/pubsub_test.go b/internal/grpcsync/pubsub_test.go index 7b24478cbebe..c9f9889c6933 100644 --- a/internal/grpcsync/pubsub_test.go +++ b/internal/grpcsync/pubsub_test.go @@ -33,7 +33,7 @@ func newTestSubscriber(chSize int) *testSubscriber { return &testSubscriber{onMsgCh: make(chan int, chSize)} } -func (ts *testSubscriber) OnMessage(msg interface{}) { +func (ts *testSubscriber) OnMessage(msg any) { select { case ts.onMsgCh <- msg.(int): default: diff --git a/internal/grpctest/grpctest.go b/internal/grpctest/grpctest.go index d0a2c533b855..cda2b49a064c 100644 --- a/internal/grpctest/grpctest.go +++ b/internal/grpctest/grpctest.go @@ -34,7 +34,7 @@ type errorer struct { t *testing.T } -func (e errorer) Errorf(format string, args ...interface{}) { +func (e errorer) Errorf(format string, args ...any) { atomic.StoreUint32(&lcFailed, 1) e.t.Errorf(format, args...) } @@ -85,7 +85,7 @@ func getTestFunc(t *testing.T, xv reflect.Value, name string) func(*testing.T) { // To run a specific test/subtest: // // $ go test -v -run 'TestExample/^Something$' . -func RunSubTests(t *testing.T, x interface{}) { +func RunSubTests(t *testing.T, x any) { xt := reflect.TypeOf(x) xv := reflect.ValueOf(x) diff --git a/internal/grpctest/tlogger.go b/internal/grpctest/tlogger.go index bbb2a2ff4fb0..f7f6da15284f 100644 --- a/internal/grpctest/tlogger.go +++ b/internal/grpctest/tlogger.go @@ -90,7 +90,7 @@ func getCallingPrefix(depth int) (string, error) { } // log logs the message with the specified parameters to the tLogger. -func (g *tLogger) log(ltype logType, depth int, format string, args ...interface{}) { +func (g *tLogger) log(ltype logType, depth int, format string, args ...any) { g.mu.Lock() defer g.mu.Unlock() prefix, err := getCallingPrefix(callingFrame + depth) @@ -98,7 +98,7 @@ func (g *tLogger) log(ltype logType, depth int, format string, args ...interface g.t.Error(err) return } - args = append([]interface{}{ltype.String() + " " + prefix}, args...) + args = append([]any{ltype.String() + " " + prefix}, args...) args = append(args, fmt.Sprintf(" (t=+%s)", time.Since(g.start))) if format == "" { @@ -194,67 +194,67 @@ func (g *tLogger) expected(s string) bool { return false } -func (g *tLogger) Info(args ...interface{}) { +func (g *tLogger) Info(args ...any) { g.log(infoLog, 0, "", args...) } -func (g *tLogger) Infoln(args ...interface{}) { +func (g *tLogger) Infoln(args ...any) { g.log(infoLog, 0, "", args...) } -func (g *tLogger) Infof(format string, args ...interface{}) { +func (g *tLogger) Infof(format string, args ...any) { g.log(infoLog, 0, format, args...) } -func (g *tLogger) InfoDepth(depth int, args ...interface{}) { +func (g *tLogger) InfoDepth(depth int, args ...any) { g.log(infoLog, depth, "", args...) } -func (g *tLogger) Warning(args ...interface{}) { +func (g *tLogger) Warning(args ...any) { g.log(warningLog, 0, "", args...) } -func (g *tLogger) Warningln(args ...interface{}) { +func (g *tLogger) Warningln(args ...any) { g.log(warningLog, 0, "", args...) } -func (g *tLogger) Warningf(format string, args ...interface{}) { +func (g *tLogger) Warningf(format string, args ...any) { g.log(warningLog, 0, format, args...) } -func (g *tLogger) WarningDepth(depth int, args ...interface{}) { +func (g *tLogger) WarningDepth(depth int, args ...any) { g.log(warningLog, depth, "", args...) } -func (g *tLogger) Error(args ...interface{}) { +func (g *tLogger) Error(args ...any) { g.log(errorLog, 0, "", args...) } -func (g *tLogger) Errorln(args ...interface{}) { +func (g *tLogger) Errorln(args ...any) { g.log(errorLog, 0, "", args...) } -func (g *tLogger) Errorf(format string, args ...interface{}) { +func (g *tLogger) Errorf(format string, args ...any) { g.log(errorLog, 0, format, args...) } -func (g *tLogger) ErrorDepth(depth int, args ...interface{}) { +func (g *tLogger) ErrorDepth(depth int, args ...any) { g.log(errorLog, depth, "", args...) } -func (g *tLogger) Fatal(args ...interface{}) { +func (g *tLogger) Fatal(args ...any) { g.log(fatalLog, 0, "", args...) } -func (g *tLogger) Fatalln(args ...interface{}) { +func (g *tLogger) Fatalln(args ...any) { g.log(fatalLog, 0, "", args...) } -func (g *tLogger) Fatalf(format string, args ...interface{}) { +func (g *tLogger) Fatalf(format string, args ...any) { g.log(fatalLog, 0, format, args...) } -func (g *tLogger) FatalDepth(depth int, args ...interface{}) { +func (g *tLogger) FatalDepth(depth int, args ...any) { g.log(fatalLog, depth, "", args...) } diff --git a/internal/hierarchy/hierarchy.go b/internal/hierarchy/hierarchy.go index 884ae22292dc..c3baac3643ce 100644 --- a/internal/hierarchy/hierarchy.go +++ b/internal/hierarchy/hierarchy.go @@ -32,7 +32,7 @@ const pathKey = pathKeyType("grpc.internal.address.hierarchical_path") type pathValue []string -func (p pathValue) Equal(o interface{}) bool { +func (p pathValue) Equal(o any) bool { op, ok := o.(pathValue) if !ok { return false diff --git a/internal/internal.go b/internal/internal.go index 9067abc98f77..8fb17727cc74 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -30,7 +30,7 @@ import ( var ( // WithHealthCheckFunc is set by dialoptions.go - WithHealthCheckFunc interface{} // func (HealthChecker) DialOption + WithHealthCheckFunc any // func (HealthChecker) DialOption // HealthCheckFunc is used to provide client-side LB channel health checking HealthCheckFunc HealthChecker // BalancerUnregister is exported by package balancer to unregister a balancer. @@ -39,7 +39,7 @@ var ( // default, but tests may wish to set it lower for convenience. KeepaliveMinPingTime = 10 * time.Second // ParseServiceConfig parses a JSON representation of the service config. - ParseServiceConfig interface{} // func(string) *serviceconfig.ParseResult + ParseServiceConfig any // func(string) *serviceconfig.ParseResult // EqualServiceConfigForTesting is for testing service config generation and // parsing. Both a and b should be returned by ParseServiceConfig. // This function compares the config without rawJSON stripped, in case the @@ -49,33 +49,33 @@ var ( // given name. This is set by package certprovider for use from xDS // bootstrap code while parsing certificate provider configs in the // bootstrap file. - GetCertificateProviderBuilder interface{} // func(string) certprovider.Builder + GetCertificateProviderBuilder any // func(string) certprovider.Builder // GetXDSHandshakeInfoForTesting returns a pointer to the xds.HandshakeInfo // stored in the passed in attributes. This is set by // credentials/xds/xds.go. - GetXDSHandshakeInfoForTesting interface{} // func (*attributes.Attributes) *xds.HandshakeInfo + GetXDSHandshakeInfoForTesting any // func (*attributes.Attributes) *xds.HandshakeInfo // GetServerCredentials returns the transport credentials configured on a // gRPC server. An xDS-enabled server needs to know what type of credentials // is configured on the underlying gRPC server. This is set by server.go. - GetServerCredentials interface{} // func (*grpc.Server) credentials.TransportCredentials + GetServerCredentials any // func (*grpc.Server) credentials.TransportCredentials // CanonicalString returns the canonical string of the code defined here: // https://github.com/grpc/grpc/blob/master/doc/statuscodes.md. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - CanonicalString interface{} // func (codes.Code) string + CanonicalString any // func (codes.Code) string // DrainServerTransports initiates a graceful close of existing connections // on a gRPC server accepted on the provided listener address. An // xDS-enabled server invokes this method on a grpc.Server when a particular // listener moves to "not-serving" mode. - DrainServerTransports interface{} // func(*grpc.Server, string) + DrainServerTransports any // func(*grpc.Server, string) // AddGlobalServerOptions adds an array of ServerOption that will be // effective globally for newly created servers. The priority will be: 1. // user-provided; 2. this method; 3. default values. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - AddGlobalServerOptions interface{} // func(opt ...ServerOption) + AddGlobalServerOptions any // func(opt ...ServerOption) // ClearGlobalServerOptions clears the array of extra ServerOption. This // method is useful in testing and benchmarking. // @@ -88,14 +88,14 @@ var ( // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - AddGlobalDialOptions interface{} // func(opt ...DialOption) + AddGlobalDialOptions any // func(opt ...DialOption) // DisableGlobalDialOptions returns a DialOption that prevents the // ClientConn from applying the global DialOptions (set via // AddGlobalDialOptions). // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - DisableGlobalDialOptions interface{} // func() grpc.DialOption + DisableGlobalDialOptions any // func() grpc.DialOption // ClearGlobalDialOptions clears the array of extra DialOption. This // method is useful in testing and benchmarking. // @@ -104,26 +104,26 @@ var ( ClearGlobalDialOptions func() // JoinDialOptions combines the dial options passed as arguments into a // single dial option. - JoinDialOptions interface{} // func(...grpc.DialOption) grpc.DialOption + JoinDialOptions any // func(...grpc.DialOption) grpc.DialOption // JoinServerOptions combines the server options passed as arguments into a // single server option. - JoinServerOptions interface{} // func(...grpc.ServerOption) grpc.ServerOption + JoinServerOptions any // func(...grpc.ServerOption) grpc.ServerOption // WithBinaryLogger returns a DialOption that specifies the binary logger // for a ClientConn. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - WithBinaryLogger interface{} // func(binarylog.Logger) grpc.DialOption + WithBinaryLogger any // func(binarylog.Logger) grpc.DialOption // BinaryLogger returns a ServerOption that can set the binary logger for a // server. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. - BinaryLogger interface{} // func(binarylog.Logger) grpc.ServerOption + BinaryLogger any // func(binarylog.Logger) grpc.ServerOption // SubscribeToConnectivityStateChanges adds a grpcsync.Subscriber to a provided grpc.ClientConn - SubscribeToConnectivityStateChanges interface{} // func(*grpc.ClientConn, grpcsync.Subscriber) + SubscribeToConnectivityStateChanges any // func(*grpc.ClientConn, grpcsync.Subscriber) // NewXDSResolverWithConfigForTesting creates a new xds resolver builder using // the provided xds bootstrap config instead of the global configuration from @@ -134,7 +134,7 @@ var ( // // This function should ONLY be used for testing and may not work with some // other features, including the CSDS service. - NewXDSResolverWithConfigForTesting interface{} // func([]byte) (resolver.Builder, error) + NewXDSResolverWithConfigForTesting any // func([]byte) (resolver.Builder, error) // RegisterRLSClusterSpecifierPluginForTesting registers the RLS Cluster // Specifier Plugin for testing purposes, regardless of the XDSRLS environment @@ -166,7 +166,7 @@ var ( UnregisterRBACHTTPFilterForTesting func() // ORCAAllowAnyMinReportingInterval is for examples/orca use ONLY. - ORCAAllowAnyMinReportingInterval interface{} // func(so *orca.ServiceOptions) + ORCAAllowAnyMinReportingInterval any // func(so *orca.ServiceOptions) // GRPCResolverSchemeExtraMetadata determines when gRPC will add extra // metadata to RPCs. @@ -181,7 +181,7 @@ var ( // // The health checking protocol is defined at: // https://github.com/grpc/grpc/blob/master/doc/health-checking.md -type HealthChecker func(ctx context.Context, newStream func(string) (interface{}, error), setConnectivityState func(connectivity.State, error), serviceName string) error +type HealthChecker func(ctx context.Context, newStream func(string) (any, error), setConnectivityState func(connectivity.State, error), serviceName string) error const ( // CredsBundleModeFallback switches GoogleDefaultCreds to fallback mode. diff --git a/internal/leakcheck/leakcheck.go b/internal/leakcheck/leakcheck.go index 80e43beb6c0e..68c37fe4184d 100644 --- a/internal/leakcheck/leakcheck.go +++ b/internal/leakcheck/leakcheck.go @@ -97,7 +97,7 @@ func interestingGoroutines() (gs []string) { // Errorfer is the interface that wraps the Errorf method. It's a subset of // testing.TB to make it easy to use Check. type Errorfer interface { - Errorf(format string, args ...interface{}) + Errorf(format string, args ...any) } func check(efer Errorfer, timeout time.Duration) { diff --git a/internal/leakcheck/leakcheck_test.go b/internal/leakcheck/leakcheck_test.go index 50927e9db4cd..606632cd2a21 100644 --- a/internal/leakcheck/leakcheck_test.go +++ b/internal/leakcheck/leakcheck_test.go @@ -30,7 +30,7 @@ type testErrorfer struct { errors []string } -func (e *testErrorfer) Errorf(format string, args ...interface{}) { +func (e *testErrorfer) Errorf(format string, args ...any) { e.errors = append(e.errors, fmt.Sprintf(format, args...)) e.errorCount++ } diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index c82e608e0773..900bfb716080 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -35,7 +35,7 @@ const mdKey = mdKeyType("grpc.internal.address.metadata") type mdValue metadata.MD -func (m mdValue) Equal(o interface{}) bool { +func (m mdValue) Equal(o any) bool { om, ok := o.(mdValue) if !ok { return false diff --git a/internal/pretty/pretty.go b/internal/pretty/pretty.go index 0177af4b5114..7033191375de 100644 --- a/internal/pretty/pretty.go +++ b/internal/pretty/pretty.go @@ -35,7 +35,7 @@ const jsonIndent = " " // ToJSON marshals the input into a json string. // // If marshal fails, it falls back to fmt.Sprintf("%+v"). -func ToJSON(e interface{}) string { +func ToJSON(e any) string { switch ee := e.(type) { case protov1.Message: mm := jsonpb.Marshaler{Indent: jsonIndent} diff --git a/internal/profiling/buffer/buffer.go b/internal/profiling/buffer/buffer.go index 8bf89c901458..27c8a2003cb1 100644 --- a/internal/profiling/buffer/buffer.go +++ b/internal/profiling/buffer/buffer.go @@ -170,7 +170,7 @@ func NewCircularBuffer(size uint32) (*CircularBuffer, error) { // a finite number of steps (also lock-free). Does not guarantee that push // order will be retained. Does not guarantee that the operation will succeed // if a Drain operation concurrently begins execution. -func (cb *CircularBuffer) Push(x interface{}) { +func (cb *CircularBuffer) Push(x any) { n := atomic.AddUint32(&cb.qpn, 1) & cb.qpMask qptr := atomic.LoadPointer(&cb.qp[n].q) q := (*queue)(qptr) @@ -221,10 +221,10 @@ func (cb *CircularBuffer) Push(x interface{}) { // arr that are copied is [from, to). Assumes that the result slice is already // allocated and is large enough to hold all the elements that might be copied. // Also assumes mutual exclusion on the array of pointers. -func dereferenceAppend(result []interface{}, arr []unsafe.Pointer, from, to uint32) []interface{} { +func dereferenceAppend(result []any, arr []unsafe.Pointer, from, to uint32) []any { for i := from; i < to; i++ { // We have mutual exclusion on arr, there's no need for atomics. - x := (*interface{})(arr[i]) + x := (*any)(arr[i]) if x != nil { result = append(result, *x) } @@ -235,7 +235,7 @@ func dereferenceAppend(result []interface{}, arr []unsafe.Pointer, from, to uint // Drain allocates and returns an array of things Pushed in to the circular // buffer. Push order is not maintained; that is, if B was Pushed after A, // drain may return B at a lower index than A in the returned array. -func (cb *CircularBuffer) Drain() []interface{} { +func (cb *CircularBuffer) Drain() []any { cb.drainMutex.Lock() qs := make([]*queue, len(cb.qp)) @@ -253,7 +253,7 @@ func (cb *CircularBuffer) Drain() []interface{} { } wg.Wait() - result := make([]interface{}, 0) + result := make([]any, 0) for i := 0; i < len(qs); i++ { if acquired := atomic.LoadUint32(&qs[i].acquired); acquired < qs[i].size { result = dereferenceAppend(result, qs[i].arr, 0, acquired) diff --git a/internal/profiling/buffer/buffer_test.go b/internal/profiling/buffer/buffer_test.go index a7f3b61e4afa..c816a87dac27 100644 --- a/internal/profiling/buffer/buffer_test.go +++ b/internal/profiling/buffer/buffer_test.go @@ -37,7 +37,7 @@ func Test(t *testing.T) { func (s) TestCircularBufferSerial(t *testing.T) { var size, i uint32 - var result []interface{} + var result []any size = 1 << 15 cb, err := NewCircularBuffer(size) @@ -78,7 +78,7 @@ func (s) TestCircularBufferSerial(t *testing.T) { func (s) TestCircularBufferOverflow(t *testing.T) { var size, i uint32 - var result []interface{} + var result []any size = 1 << 10 cb, err := NewCircularBuffer(size) @@ -106,7 +106,7 @@ func (s) TestCircularBufferOverflow(t *testing.T) { func (s) TestCircularBufferConcurrent(t *testing.T) { for tn := 0; tn < 2; tn++ { var size uint32 - var result []interface{} + var result []any size = 1 << 6 cb, err := NewCircularBuffer(size) diff --git a/internal/profiling/profiling.go b/internal/profiling/profiling.go index 4d8e68aab433..58f71423459e 100644 --- a/internal/profiling/profiling.go +++ b/internal/profiling/profiling.go @@ -26,10 +26,10 @@ // example, if one wants to profile the load balancing layer, which is // independent of RPC queries, a separate CircularBuffer can be used. // -// Note that the circular buffer simply takes any interface{}. In the future, -// more types of measurements (such as the number of memory allocations) could -// be measured, which might require a different type of object being pushed -// into the circular buffer. +// Note that the circular buffer simply takes any type. In the future, more +// types of measurements (such as the number of memory allocations) could be +// measured, which might require a different type of object being pushed into +// the circular buffer. package profiling import ( diff --git a/internal/resolver/config_selector.go b/internal/resolver/config_selector.go index c7a18a948adb..f0603871c93a 100644 --- a/internal/resolver/config_selector.go +++ b/internal/resolver/config_selector.go @@ -92,7 +92,7 @@ type ClientStream interface { // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. It is also // not safe to call CloseSend concurrently with SendMsg. - SendMsg(m interface{}) error + SendMsg(m any) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC @@ -101,7 +101,7 @@ type ClientStream interface { // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m interface{}) error + RecvMsg(m any) error } // ClientInterceptor is an interceptor for gRPC client streams. diff --git a/internal/status/status.go b/internal/status/status.go index b0ead4f54f82..4cf85cad9f81 100644 --- a/internal/status/status.go +++ b/internal/status/status.go @@ -49,7 +49,7 @@ func New(c codes.Code, msg string) *Status { } // Newf returns New(c, fmt.Sprintf(format, a...)). -func Newf(c codes.Code, format string, a ...interface{}) *Status { +func Newf(c codes.Code, format string, a ...any) *Status { return New(c, fmt.Sprintf(format, a...)) } @@ -64,7 +64,7 @@ func Err(c codes.Code, msg string) error { } // Errorf returns Error(c, fmt.Sprintf(format, a...)). -func Errorf(c codes.Code, format string, a ...interface{}) error { +func Errorf(c codes.Code, format string, a ...any) error { return Err(c, fmt.Sprintf(format, a...)) } @@ -120,11 +120,11 @@ func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { // Details returns a slice of details messages attached to the status. // If a detail cannot be decoded, the error is returned in place of the detail. -func (s *Status) Details() []interface{} { +func (s *Status) Details() []any { if s == nil || s.s == nil { return nil } - details := make([]interface{}, 0, len(s.s.Details)) + details := make([]any, 0, len(s.s.Details)) for _, any := range s.s.Details { detail := &ptypes.DynamicAny{} if err := ptypes.UnmarshalAny(any, detail); err != nil { diff --git a/internal/testutils/balancer.go b/internal/testutils/balancer.go index 61cb55e7c11c..43bbbf9ae560 100644 --- a/internal/testutils/balancer.go +++ b/internal/testutils/balancer.go @@ -32,9 +32,9 @@ import ( // testingLogger wraps the logging methods from testing.T. type testingLogger interface { - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) + Log(args ...any) + Logf(format string, args ...any) + Errorf(format string, args ...any) } // TestSubConn implements the SubConn interface, to be used in tests. diff --git a/internal/testutils/channel.go b/internal/testutils/channel.go index 6a08a94a099f..991d05cdde74 100644 --- a/internal/testutils/channel.go +++ b/internal/testutils/channel.go @@ -26,17 +26,17 @@ const DefaultChanBufferSize = 1 // Channel wraps a generic channel and provides a timed receive operation. type Channel struct { - ch chan interface{} + ch chan any } // Send sends value on the underlying channel. -func (c *Channel) Send(value interface{}) { +func (c *Channel) Send(value any) { c.ch <- value } // SendContext sends value on the underlying channel, or returns an error if // the context expires. -func (c *Channel) SendContext(ctx context.Context, value interface{}) error { +func (c *Channel) SendContext(ctx context.Context, value any) error { select { case c.ch <- value: return nil @@ -47,7 +47,7 @@ func (c *Channel) SendContext(ctx context.Context, value interface{}) error { // SendOrFail attempts to send value on the underlying channel. Returns true // if successful or false if the channel was full. -func (c *Channel) SendOrFail(value interface{}) bool { +func (c *Channel) SendOrFail(value any) bool { select { case c.ch <- value: return true @@ -58,7 +58,7 @@ func (c *Channel) SendOrFail(value interface{}) bool { // ReceiveOrFail returns the value on the underlying channel and true, or nil // and false if the channel was empty. -func (c *Channel) ReceiveOrFail() (interface{}, bool) { +func (c *Channel) ReceiveOrFail() (any, bool) { select { case got := <-c.ch: return got, true @@ -69,7 +69,7 @@ func (c *Channel) ReceiveOrFail() (interface{}, bool) { // Receive returns the value received on the underlying channel, or the error // returned by ctx if it is closed or cancelled. -func (c *Channel) Receive(ctx context.Context) (interface{}, error) { +func (c *Channel) Receive(ctx context.Context) (any, error) { select { case <-ctx.Done(): return nil, ctx.Err() @@ -83,7 +83,7 @@ func (c *Channel) Receive(ctx context.Context) (interface{}, error) { // It's expected to be used with a size-1 channel, to only keep the most // up-to-date item. This method is inherently racy when invoked concurrently // from multiple goroutines. -func (c *Channel) Replace(value interface{}) { +func (c *Channel) Replace(value any) { for { select { case c.ch <- value: @@ -100,5 +100,5 @@ func NewChannel() *Channel { // NewChannelWithSize returns a new Channel with a buffer of bufSize. func NewChannelWithSize(bufSize int) *Channel { - return &Channel{ch: make(chan interface{}, bufSize)} + return &Channel{ch: make(chan any, bufSize)} } diff --git a/internal/testutils/wrr.go b/internal/testutils/wrr.go index 6c9486329d41..5dcc7a8d37a4 100644 --- a/internal/testutils/wrr.go +++ b/internal/testutils/wrr.go @@ -33,7 +33,7 @@ import ( // With {a: 2, b: 3}, the Next() results will be {a, a, b, b, b}. type testWRR struct { itemsWithWeight []struct { - item interface{} + item any weight int64 } length int @@ -48,15 +48,15 @@ func NewTestWRR() wrr.WRR { return &testWRR{} } -func (twrr *testWRR) Add(item interface{}, weight int64) { +func (twrr *testWRR) Add(item any, weight int64) { twrr.itemsWithWeight = append(twrr.itemsWithWeight, struct { - item interface{} + item any weight int64 }{item: item, weight: weight}) twrr.length++ } -func (twrr *testWRR) Next() interface{} { +func (twrr *testWRR) Next() any { twrr.mu.Lock() iww := twrr.itemsWithWeight[twrr.idx] twrr.count++ diff --git a/internal/testutils/xds/bootstrap/bootstrap.go b/internal/testutils/xds/bootstrap/bootstrap.go index 786a6a4d7513..190cf028f0b5 100644 --- a/internal/testutils/xds/bootstrap/bootstrap.go +++ b/internal/testutils/xds/bootstrap/bootstrap.go @@ -158,8 +158,8 @@ type server struct { } type creds struct { - Type string `json:"type,omitempty"` - Config interface{} `json:"config,omitempty"` + Type string `json:"type,omitempty"` + Config any `json:"config,omitempty"` } type node struct { diff --git a/internal/testutils/xds/e2e/logging.go b/internal/testutils/xds/e2e/logging.go index f524c451b002..2a0925a13060 100644 --- a/internal/testutils/xds/e2e/logging.go +++ b/internal/testutils/xds/e2e/logging.go @@ -30,19 +30,19 @@ var logger = grpclog.Component("xds-e2e") // envoyproxy/go-control-plane/pkg/log. This is passed to the Snapshot cache. type serverLogger struct{} -func (l serverLogger) Debugf(format string, args ...interface{}) { +func (l serverLogger) Debugf(format string, args ...any) { msg := fmt.Sprintf(format, args...) logger.InfoDepth(1, msg) } -func (l serverLogger) Infof(format string, args ...interface{}) { +func (l serverLogger) Infof(format string, args ...any) { msg := fmt.Sprintf(format, args...) logger.InfoDepth(1, msg) } -func (l serverLogger) Warnf(format string, args ...interface{}) { +func (l serverLogger) Warnf(format string, args ...any) { msg := fmt.Sprintf(format, args...) logger.WarningDepth(1, msg) } -func (l serverLogger) Errorf(format string, args ...interface{}) { +func (l serverLogger) Errorf(format string, args ...any) { msg := fmt.Sprintf(format, args...) logger.ErrorDepth(1, msg) } diff --git a/internal/testutils/xds/e2e/server.go b/internal/testutils/xds/e2e/server.go index d81c3405440b..e3bf0de5572c 100644 --- a/internal/testutils/xds/e2e/server.go +++ b/internal/testutils/xds/e2e/server.go @@ -237,7 +237,7 @@ func (s *ManagementServer) Stop() { // resourceSlice accepts a slice of any type of proto messages and returns a // slice of types.Resource. Will panic if there is an input type mismatch. -func resourceSlice(i interface{}) []types.Resource { +func resourceSlice(i any) []types.Resource { v := reflect.ValueOf(i) rs := make([]types.Resource, v.Len()) for i := 0; i < v.Len(); i++ { diff --git a/internal/transport/controlbuf.go b/internal/transport/controlbuf.go index be5a9c81eb97..b330ccedc8ab 100644 --- a/internal/transport/controlbuf.go +++ b/internal/transport/controlbuf.go @@ -40,7 +40,7 @@ var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { } type itemNode struct { - it interface{} + it any next *itemNode } @@ -49,7 +49,7 @@ type itemList struct { tail *itemNode } -func (il *itemList) enqueue(i interface{}) { +func (il *itemList) enqueue(i any) { n := &itemNode{it: i} if il.tail == nil { il.head, il.tail = n, n @@ -61,11 +61,11 @@ func (il *itemList) enqueue(i interface{}) { // peek returns the first item in the list without removing it from the // list. -func (il *itemList) peek() interface{} { +func (il *itemList) peek() any { return il.head.it } -func (il *itemList) dequeue() interface{} { +func (il *itemList) dequeue() any { if il.head == nil { return nil } @@ -336,7 +336,7 @@ func (c *controlBuffer) put(it cbItem) error { return err } -func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it cbItem) (bool, error) { +func (c *controlBuffer) executeAndPut(f func(it any) bool, it cbItem) (bool, error) { var wakeUp bool c.mu.Lock() if c.err != nil { @@ -373,7 +373,7 @@ func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it cbItem) (b } // Note argument f should never be nil. -func (c *controlBuffer) execute(f func(it interface{}) bool, it interface{}) (bool, error) { +func (c *controlBuffer) execute(f func(it any) bool, it any) (bool, error) { c.mu.Lock() if c.err != nil { c.mu.Unlock() @@ -387,7 +387,7 @@ func (c *controlBuffer) execute(f func(it interface{}) bool, it interface{}) (bo return true, nil } -func (c *controlBuffer) get(block bool) (interface{}, error) { +func (c *controlBuffer) get(block bool) (any, error) { for { c.mu.Lock() if c.err != nil { @@ -830,7 +830,7 @@ func (l *loopyWriter) goAwayHandler(g *goAway) error { return nil } -func (l *loopyWriter) handle(i interface{}) error { +func (l *loopyWriter) handle(i any) error { switch i := i.(type) { case *incomingWindowUpdate: l.incomingWindowUpdateHandler(i) diff --git a/internal/transport/http2_client.go b/internal/transport/http2_client.go index 52b88c32b15b..afcda3602f0c 100644 --- a/internal/transport/http2_client.go +++ b/internal/transport/http2_client.go @@ -762,7 +762,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, firstTry := true var ch chan struct{} transportDrainRequired := false - checkForStreamQuota := func(it interface{}) bool { + checkForStreamQuota := func(it any) bool { if t.streamQuota <= 0 { // Can go negative if server decreases it. if firstTry { t.waitingStreams++ @@ -800,7 +800,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, return true } var hdrListSizeErr error - checkForHeaderListSize := func(it interface{}) bool { + checkForHeaderListSize := func(it any) bool { if t.maxSendHeaderListSize == nil { return true } @@ -815,7 +815,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, return true } for { - success, err := t.controlBuf.executeAndPut(func(it interface{}) bool { + success, err := t.controlBuf.executeAndPut(func(it any) bool { return checkForHeaderListSize(it) && checkForStreamQuota(it) }, hdr) if err != nil { @@ -927,7 +927,7 @@ func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2. rst: rst, rstCode: rstCode, } - addBackStreamQuota := func(interface{}) bool { + addBackStreamQuota := func(any) bool { t.streamQuota++ if t.streamQuota > 0 && t.waitingStreams > 0 { select { @@ -1080,7 +1080,7 @@ func (t *http2Client) updateWindow(s *Stream, n uint32) { // for the transport and the stream based on the current bdp // estimation. func (t *http2Client) updateFlowControl(n uint32) { - updateIWS := func(interface{}) bool { + updateIWS := func(any) bool { t.initialWindowSize = int32(n) t.mu.Lock() for _, s := range t.activeStreams { @@ -1233,7 +1233,7 @@ func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { } updateFuncs = append(updateFuncs, updateStreamQuota) } - t.controlBuf.executeAndPut(func(interface{}) bool { + t.controlBuf.executeAndPut(func(any) bool { for _, f := range updateFuncs { f() } diff --git a/internal/transport/http2_server.go b/internal/transport/http2_server.go index c48091f6c0a6..8d3a353c1d58 100644 --- a/internal/transport/http2_server.go +++ b/internal/transport/http2_server.go @@ -855,7 +855,7 @@ func (t *http2Server) handleSettings(f *http2.SettingsFrame) { } return nil }) - t.controlBuf.executeAndPut(func(interface{}) bool { + t.controlBuf.executeAndPut(func(any) bool { for _, f := range updateFuncs { f() } @@ -939,7 +939,7 @@ func appendHeaderFieldsFromMD(headerFields []hpack.HeaderField, md metadata.MD) return headerFields } -func (t *http2Server) checkForHeaderListSize(it interface{}) bool { +func (t *http2Server) checkForHeaderListSize(it any) bool { if t.maxSendHeaderListSize == nil { return true } diff --git a/internal/transport/http_util.go b/internal/transport/http_util.go index add1e9b2cc04..1958140082b3 100644 --- a/internal/transport/http_util.go +++ b/internal/transport/http_util.go @@ -441,7 +441,7 @@ func getWriteBufferPool(writeBufferSize int) *sync.Pool { return pool } pool = &sync.Pool{ - New: func() interface{} { + New: func() any { b := make([]byte, size) return &b }, diff --git a/internal/transport/transport.go b/internal/transport/transport.go index 3828b3e4a8d1..99e184a13978 100644 --- a/internal/transport/transport.go +++ b/internal/transport/transport.go @@ -56,7 +56,7 @@ type bufferPool struct { func newBufferPool() *bufferPool { return &bufferPool{ pool: sync.Pool{ - New: func() interface{} { + New: func() any { return new(bytes.Buffer) }, }, @@ -739,7 +739,7 @@ type ServerTransport interface { } // connectionErrorf creates an ConnectionError with the specified error description. -func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError { +func connectionErrorf(temp bool, e error, format string, a ...any) ConnectionError { return ConnectionError{ Desc: fmt.Sprintf(format, a...), temp: temp, diff --git a/internal/wrr/edf.go b/internal/wrr/edf.go index b4fb3f9d3bea..a06656f46400 100644 --- a/internal/wrr/edf.go +++ b/internal/wrr/edf.go @@ -43,7 +43,7 @@ type edfEntry struct { deadline float64 weight int64 orderOffset uint64 - item interface{} + item any } // edfPriorityQueue is a heap.Interface implementation for edfEntry elements. @@ -55,17 +55,17 @@ func (pq edfPriorityQueue) Less(i, j int) bool { } func (pq edfPriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } -func (pq *edfPriorityQueue) Push(x interface{}) { +func (pq *edfPriorityQueue) Push(x any) { *pq = append(*pq, x.(*edfEntry)) } -func (pq *edfPriorityQueue) Pop() interface{} { +func (pq *edfPriorityQueue) Pop() any { old := *pq *pq = old[0 : len(old)-1] return old[len(old)-1] } -func (edf *edfWrr) Add(item interface{}, weight int64) { +func (edf *edfWrr) Add(item any, weight int64) { edf.lock.Lock() defer edf.lock.Unlock() entry := edfEntry{ @@ -78,7 +78,7 @@ func (edf *edfWrr) Add(item interface{}, weight int64) { heap.Push(&edf.items, &entry) } -func (edf *edfWrr) Next() interface{} { +func (edf *edfWrr) Next() any { edf.lock.Lock() defer edf.lock.Unlock() if len(edf.items) == 0 { diff --git a/internal/wrr/random.go b/internal/wrr/random.go index 6d5eb7d46209..25bbd82594d6 100644 --- a/internal/wrr/random.go +++ b/internal/wrr/random.go @@ -27,7 +27,7 @@ import ( // weightedItem is a wrapped weighted item that is used to implement weighted random algorithm. type weightedItem struct { - item interface{} + item any weight int64 accumulatedWeight int64 } @@ -51,7 +51,7 @@ func NewRandom() WRR { var grpcrandInt63n = grpcrand.Int63n -func (rw *randomWRR) Next() (item interface{}) { +func (rw *randomWRR) Next() (item any) { rw.mu.RLock() defer rw.mu.RUnlock() if len(rw.items) == 0 { @@ -71,7 +71,7 @@ func (rw *randomWRR) Next() (item interface{}) { return rw.items[i].item } -func (rw *randomWRR) Add(item interface{}, weight int64) { +func (rw *randomWRR) Add(item any, weight int64) { rw.mu.Lock() defer rw.mu.Unlock() accumulatedWeight := weight diff --git a/internal/wrr/wrr.go b/internal/wrr/wrr.go index d46bfad86ef4..d0d82cf4f015 100644 --- a/internal/wrr/wrr.go +++ b/internal/wrr/wrr.go @@ -24,9 +24,9 @@ type WRR interface { // Add adds an item with weight to the WRR set. // // Add and Next need to be thread safe. - Add(item interface{}, weight int64) + Add(item any, weight int64) // Next returns the next picked item. // // Add and Next need to be thread safe. - Next() interface{} + Next() any } diff --git a/internal/xds/rbac/converter_test.go b/internal/xds/rbac/converter_test.go index 9b8004f7bd5c..222e504d82c3 100644 --- a/internal/xds/rbac/converter_test.go +++ b/internal/xds/rbac/converter_test.go @@ -61,7 +61,7 @@ func (s) TestBuildLoggerErrors(t *testing.T) { loggerConfig: &v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, ""), + TypedConfig: createUDPATypedStruct(t, map[string]any{}, ""), }, }, expectedError: "field TypedConfig.TypeURL cannot be an empty string", @@ -71,7 +71,7 @@ func (s) TestBuildLoggerErrors(t *testing.T) { loggerConfig: &v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "UnregisteredLogger", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "UnregisteredLogger"), + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "UnregisteredLogger"), }, IsOptional: false, }, @@ -82,7 +82,7 @@ func (s) TestBuildLoggerErrors(t *testing.T) { loggerConfig: &v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerCustomConfig", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{"abc": "BADVALUE", "xyz": "123"}, "fail to parse custom config_TestAuditLoggerCustomConfig")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{"abc": "BADVALUE", "xyz": "123"}, "fail to parse custom config_TestAuditLoggerCustomConfig")}, IsOptional: false, }, expectedError: "custom config could not be parsed", @@ -92,7 +92,7 @@ func (s) TestBuildLoggerErrors(t *testing.T) { loggerConfig: &v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "UnregisteredLogger", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "no registered logger but optional passes_UnregisteredLogger"), + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "no registered logger but optional passes_UnregisteredLogger"), }, IsOptional: true, }, @@ -137,7 +137,7 @@ func (s) TestBuildLoggerKnownTypes(t *testing.T) { loggerConfig: &v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ AuditLogger: &v3corepb.TypedExtensionConfig{ Name: stdout.Name, - TypedConfig: createXDSTypedStruct(t, map[string]interface{}{}, stdout.Name), + TypedConfig: createXDSTypedStruct(t, map[string]any{}, stdout.Name), }, IsOptional: false, }, diff --git a/internal/xds/rbac/rbac_engine_test.go b/internal/xds/rbac/rbac_engine_test.go index 94464cf184ab..d0c3ae7af3e8 100644 --- a/internal/xds/rbac/rbac_engine_test.go +++ b/internal/xds/rbac/rbac_engine_test.go @@ -454,7 +454,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "SimpleAuditLogger_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "SimpleAuditLogger_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -482,7 +482,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerCustomConfig", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{"abc": 123, "xyz": "123"}, "AuditLoggerCustomConfig_TestAuditLoggerCustomConfig")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{"abc": 123, "xyz": "123"}, "AuditLoggerCustomConfig_TestAuditLoggerCustomConfig")}, IsOptional: false, }, }, @@ -511,7 +511,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerCustomConfig", - TypedConfig: createXDSTypedStruct(t, map[string]interface{}{"abc": 123, "xyz": "123"}, "AuditLoggerCustomConfigXdsTypedStruct_TestAuditLoggerCustomConfig")}, + TypedConfig: createXDSTypedStruct(t, map[string]any{"abc": 123, "xyz": "123"}, "AuditLoggerCustomConfigXdsTypedStruct_TestAuditLoggerCustomConfig")}, IsOptional: false, }, }, @@ -540,7 +540,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "UnsupportedLogger", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "Missing Optional AuditLogger doesn't fail_UnsupportedLogger")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "Missing Optional AuditLogger doesn't fail_UnsupportedLogger")}, IsOptional: true, }, }, @@ -568,7 +568,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "UnsupportedLogger", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "Missing Non-Optional AuditLogger fails_UnsupportedLogger")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "Missing Non-Optional AuditLogger fails_UnsupportedLogger")}, IsOptional: false, }, }, @@ -626,7 +626,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerCustomConfig", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{"abc": "BADVALUE", "xyz": "123"}, "Cannot_parse_bad_CustomConfig_TestAuditLoggerCustomConfig")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{"abc": "BADVALUE", "xyz": "123"}, "Cannot_parse_bad_CustomConfig_TestAuditLoggerCustomConfig")}, IsOptional: false, }, }, @@ -655,7 +655,7 @@ func (s) TestNewChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerCustomConfig", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{"abc": 123, "xyz": "123"}, "")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{"abc": 123, "xyz": "123"}, "")}, IsOptional: false, }, }, @@ -1248,7 +1248,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_ALLOW_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_ALLOW_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1271,7 +1271,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_ALLOW_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_ALLOW_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1374,7 +1374,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1397,7 +1397,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1513,7 +1513,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_NONE_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_NONE_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1536,7 +1536,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_NONE_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_NONE_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1614,7 +1614,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_AND_ALLOW_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_AND_ALLOW_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1637,7 +1637,7 @@ func (s) TestChainEngine(t *testing.T) { LoggerConfigs: []*v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{ {AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "TestAuditLoggerBuffer", - TypedConfig: createUDPATypedStruct(t, map[string]interface{}{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_AND_ALLOW_TestAuditLoggerBuffer")}, + TypedConfig: createUDPATypedStruct(t, map[string]any{}, "AuditLoggingAllowAndDenyPolicy_ON_DENY_AND_ALLOW_TestAuditLoggerBuffer")}, IsOptional: false, }, }, @@ -1890,7 +1890,7 @@ func (b *TestAuditLoggerCustomConfigBuilder) Name() string { } // Builds custom configs for audit logger RBAC protos. -func createUDPATypedStruct(t *testing.T, in map[string]interface{}, name string) *anypb.Any { +func createUDPATypedStruct(t *testing.T, in map[string]any, name string) *anypb.Any { t.Helper() pb, err := structpb.NewStruct(in) if err != nil { @@ -1912,7 +1912,7 @@ func createUDPATypedStruct(t *testing.T, in map[string]interface{}, name string) } // Builds custom configs for audit logger RBAC protos. -func createXDSTypedStruct(t *testing.T, in map[string]interface{}, name string) *anypb.Any { +func createXDSTypedStruct(t *testing.T, in map[string]any, name string) *anypb.Any { t.Helper() pb, err := structpb.NewStruct(in) if err != nil { diff --git a/interop/client/client.go b/interop/client/client.go index 845ad79dead1..7f04be0c152e 100644 --- a/interop/client/client.go +++ b/interop/client/client.go @@ -249,7 +249,7 @@ func main() { opts = append(opts, grpc.WithDisableServiceConfig(), grpc.WithDefaultServiceConfig(*serviceConfigJSON)) } if addMd := parseAdditionalMetadataFlag(); addMd != nil { - unaryAddMd := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + unaryAddMd := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { ctx = metadata.AppendToOutgoingContext(ctx, addMd...) return invoker(ctx, method, req, reply, cc, opts...) } diff --git a/interop/observability/go.mod b/interop/observability/go.mod index 6edb9845c4cb..4de7ebb8995a 100644 --- a/interop/observability/go.mod +++ b/interop/observability/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/interop/observability -go 1.17 +go 1.19 require ( google.golang.org/grpc v1.56.2 diff --git a/orca/call_metrics.go b/orca/call_metrics.go index 558c7bce6a8e..157dad49c657 100644 --- a/orca/call_metrics.go +++ b/orca/call_metrics.go @@ -135,8 +135,8 @@ func CallMetricsServerOption(smp ServerMetricsProvider) grpc.ServerOption { return joinServerOptions(grpc.ChainUnaryInterceptor(unaryInt(smp)), grpc.ChainStreamInterceptor(streamInt(smp))) } -func unaryInt(smp ServerMetricsProvider) func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func unaryInt(smp ServerMetricsProvider) func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { // We don't allocate the metric recorder here. It will be allocated the // first time the user calls CallMetricsRecorderFromContext(). rw := &recorderWrapper{smp: smp} @@ -155,8 +155,8 @@ func unaryInt(smp ServerMetricsProvider) func(ctx context.Context, req interface } } -func streamInt(smp ServerMetricsProvider) func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func streamInt(smp ServerMetricsProvider) func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { // We don't allocate the metric recorder here. It will be allocated the // first time the user calls CallMetricsRecorderFromContext(). rw := &recorderWrapper{smp: smp} diff --git a/orca/call_metrics_test.go b/orca/call_metrics_test.go index b0e6af646c91..474ac710b55b 100644 --- a/orca/call_metrics_test.go +++ b/orca/call_metrics_test.go @@ -73,7 +73,7 @@ func (s) TestE2ECallMetricsUnary(t *testing.T) { // An interceptor to injects custom backend metrics, added only when // the injectMetrics field in the test is set. - injectingInterceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + injectingInterceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { recorder := orca.CallMetricsRecorderFromContext(ctx) if recorder == nil { err := errors.New("Failed to retrieve per-RPC custom metrics recorder from the RPC context") @@ -179,7 +179,7 @@ func (s) TestE2ECallMetricsStreaming(t *testing.T) { // An interceptor which injects custom backend metrics, added only // when the injectMetrics field in the test is set. - injectingInterceptor := func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + injectingInterceptor := func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { recorder := orca.CallMetricsRecorderFromContext(ss.Context()) if recorder == nil { err := errors.New("Failed to retrieve per-RPC custom metrics recorder from the RPC context") diff --git a/orca/internal/internal.go b/orca/internal/internal.go index 35b899d9e877..d1425c3e7164 100644 --- a/orca/internal/internal.go +++ b/orca/internal/internal.go @@ -35,7 +35,7 @@ import ( // configured via ServiceOptions, to a minimum of 30s. // // For testing purposes only. -var AllowAnyMinReportingInterval interface{} // func(*ServiceOptions) +var AllowAnyMinReportingInterval any // func(*ServiceOptions) // DefaultBackoffFunc is used by the producer to control its backoff behavior. // diff --git a/orca/orca.go b/orca/orca.go index 6b475562b1b9..d0cb3720c8ac 100644 --- a/orca/orca.go +++ b/orca/orca.go @@ -44,7 +44,7 @@ var logger = grpclog.Component("orca-backend-metrics") // import cycle. Hence this roundabout method is used. type loadParser struct{} -func (loadParser) Parse(md metadata.MD) interface{} { +func (loadParser) Parse(md metadata.MD) any { lr, err := internal.ToLoadReport(md) if err != nil { logger.Infof("Parse failed: %v", err) diff --git a/orca/producer.go b/orca/producer.go index ce108aad65ca..2d58725547fc 100644 --- a/orca/producer.go +++ b/orca/producer.go @@ -37,7 +37,7 @@ import ( type producerBuilder struct{} // Build constructs and returns a producer and its cleanup function -func (*producerBuilder) Build(cci interface{}) (balancer.Producer, func()) { +func (*producerBuilder) Build(cci any) (balancer.Producer, func()) { p := &producer{ client: v3orcaservicegrpc.NewOpenRcaServiceClient(cci.(grpc.ClientConnInterface)), intervals: make(map[time.Duration]int), diff --git a/orca/producer_test.go b/orca/producer_test.go index 212cf2500f6b..ecaf57e0631e 100644 --- a/orca/producer_test.go +++ b/orca/producer_test.go @@ -212,13 +212,13 @@ type fakeORCAService struct { v3orcaservicegrpc.UnimplementedOpenRcaServiceServer reqCh chan *v3orcaservicepb.OrcaLoadReportRequest - respCh chan interface{} // either *v3orcapb.OrcaLoadReport or error + respCh chan any // either *v3orcapb.OrcaLoadReport or error } func newFakeORCAService() *fakeORCAService { return &fakeORCAService{ reqCh: make(chan *v3orcaservicepb.OrcaLoadReportRequest), - respCh: make(chan interface{}), + respCh: make(chan any), } } diff --git a/preloader.go b/preloader.go index cd45547854f0..73bd63364335 100644 --- a/preloader.go +++ b/preloader.go @@ -37,7 +37,7 @@ type PreparedMsg struct { } // Encode marshalls and compresses the message using the codec and compressor for the stream. -func (p *PreparedMsg) Encode(s Stream, msg interface{}) error { +func (p *PreparedMsg) Encode(s Stream, msg any) error { ctx := s.Context() rpcInfo, ok := rpcInfoFromContext(ctx) if !ok { diff --git a/reflection/serverreflection_test.go b/reflection/serverreflection_test.go index e61fd22d5a18..b17fa25d3d1c 100644 --- a/reflection/serverreflection_test.go +++ b/reflection/serverreflection_test.go @@ -604,7 +604,7 @@ func testListServices(t *testing.T, stream v1reflectiongrpc.ServerReflection_Ser } func registerDynamicProto(srv *grpc.Server, fdp *descriptorpb.FileDescriptorProto, fd protoreflect.FileDescriptor) { - type emptyInterface interface{} + type emptyInterface any for i := 0; i < fd.Services().Len(); i++ { s := fd.Services().Get(i) diff --git a/resolver/map.go b/resolver/map.go index efcb7f3efd82..804be887de0a 100644 --- a/resolver/map.go +++ b/resolver/map.go @@ -20,7 +20,7 @@ package resolver type addressMapEntry struct { addr Address - value interface{} + value any } // AddressMap is a map of addresses to arbitrary values taking into account @@ -69,7 +69,7 @@ func (l addressMapEntryList) find(addr Address) int { } // Get returns the value for the address in the map, if present. -func (a *AddressMap) Get(addr Address) (value interface{}, ok bool) { +func (a *AddressMap) Get(addr Address) (value any, ok bool) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { @@ -79,7 +79,7 @@ func (a *AddressMap) Get(addr Address) (value interface{}, ok bool) { } // Set updates or adds the value to the address in the map. -func (a *AddressMap) Set(addr Address, value interface{}) { +func (a *AddressMap) Set(addr Address, value any) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { @@ -127,8 +127,8 @@ func (a *AddressMap) Keys() []Address { } // Values returns a slice of all current map values. -func (a *AddressMap) Values() []interface{} { - ret := make([]interface{}, 0, a.Len()) +func (a *AddressMap) Values() []any { + ret := make([]any, 0, a.Len()) for _, entryList := range a.m { for _, entry := range entryList { ret = append(ret, entry.value) diff --git a/resolver/resolver.go b/resolver/resolver.go index f3310bc6c540..081e6f26f7bd 100644 --- a/resolver/resolver.go +++ b/resolver/resolver.go @@ -113,7 +113,7 @@ type Address struct { // to make load balancing decision. // // Deprecated: use Attributes instead. - Metadata interface{} + Metadata any } // Equal returns whether a and o are identical. Metadata is compared directly, diff --git a/rpc_util.go b/rpc_util.go index a844d28f49d0..56451d07758b 100644 --- a/rpc_util.go +++ b/rpc_util.go @@ -75,7 +75,7 @@ func NewGZIPCompressorWithLevel(level int) (Compressor, error) { } return &gzipCompressor{ pool: sync.Pool{ - New: func() interface{} { + New: func() any { w, err := gzip.NewWriterLevel(io.Discard, level) if err != nil { panic(err) @@ -626,7 +626,7 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt // encode serializes msg and returns a buffer containing the message, or an // error if it is too large to be transmitted by grpc. If msg is nil, it // generates an empty message. -func encode(c baseCodec, msg interface{}) ([]byte, error) { +func encode(c baseCodec, msg any) ([]byte, error) { if msg == nil { // NOTE: typed nils will not be caught by this check return nil, nil } @@ -693,7 +693,7 @@ func msgHeader(data, compData []byte) (hdr []byte, payload []byte) { return hdr, data } -func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload { +func outPayload(client bool, msg any, data, payload []byte, t time.Time) *stats.OutPayload { return &stats.OutPayload{ Client: client, Payload: msg, @@ -792,7 +792,7 @@ func decompress(compressor encoding.Compressor, d []byte, maxReceiveMessageSize // For the two compressor parameters, both should not be set, but if they are, // dc takes precedence over compressor. // TODO(dfawley): wrap the old compressor/decompressor using the new API? -func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error { +func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m any, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error { buf, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor) if err != nil { return err @@ -863,7 +863,7 @@ func ErrorDesc(err error) string { // Errorf returns nil if c is OK. // // Deprecated: use status.Errorf instead. -func Errorf(c codes.Code, format string, a ...interface{}) error { +func Errorf(c codes.Code, format string, a ...any) error { return status.Errorf(c, format, a...) } diff --git a/security/advancedtls/crl.go b/security/advancedtls/crl.go index bb490a5c8dba..207c7f81a2ef 100644 --- a/security/advancedtls/crl.go +++ b/security/advancedtls/crl.go @@ -50,9 +50,9 @@ var grpclogLogger = grpclog.Component("advancedtls") // A fixed size lru cache from golang-lru is recommended. type Cache interface { // Add adds a value to the cache. - Add(key, value interface{}) bool + Add(key, value any) bool // Get looks up a key's value from the cache. - Get(key interface{}) (value interface{}, ok bool) + Get(key any) (value any, ok bool) } // RevocationConfig contains options for CRL lookup. diff --git a/security/advancedtls/crl_deprecated.go b/security/advancedtls/crl_deprecated.go index a54a2f6e55c5..fc83f72ebb3f 100644 --- a/security/advancedtls/crl_deprecated.go +++ b/security/advancedtls/crl_deprecated.go @@ -50,9 +50,9 @@ var grpclogLogger = grpclog.Component("advancedtls") // A fixed size lru cache from golang-lru is recommended. type Cache interface { // Add adds a value to the cache. - Add(key, value interface{}) bool + Add(key, value any) bool // Get looks up a key's value from the cache. - Get(key interface{}) (value interface{}, ok bool) + Get(key any) (value any, ok bool) } // RevocationConfig contains options for CRL lookup. diff --git a/security/advancedtls/crl_deprecated_test.go b/security/advancedtls/crl_deprecated_test.go index f51ab95d00ce..20e230cf25e6 100644 --- a/security/advancedtls/crl_deprecated_test.go +++ b/security/advancedtls/crl_deprecated_test.go @@ -367,7 +367,7 @@ func TestCachedCRL(t *testing.T) { tests := []struct { desc string - val interface{} + val any ok bool }{ { diff --git a/security/advancedtls/crl_test.go b/security/advancedtls/crl_test.go index 021f10d35ae5..2821f2bd494d 100644 --- a/security/advancedtls/crl_test.go +++ b/security/advancedtls/crl_test.go @@ -366,7 +366,7 @@ func TestCachedCRL(t *testing.T) { tests := []struct { desc string - val interface{} + val any ok bool }{ { diff --git a/security/advancedtls/examples/go.mod b/security/advancedtls/examples/go.mod index 1af6823ac03d..51db9fe1a7f1 100644 --- a/security/advancedtls/examples/go.mod +++ b/security/advancedtls/examples/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/security/advancedtls/examples -go 1.17 +go 1.19 require ( google.golang.org/grpc v1.56.2 diff --git a/security/advancedtls/go.mod b/security/advancedtls/go.mod index ea6f2be703ae..00bb51de9215 100644 --- a/security/advancedtls/go.mod +++ b/security/advancedtls/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/security/advancedtls -go 1.17 +go 1.19 require ( github.com/hashicorp/golang-lru v0.5.4 diff --git a/security/authorization/engine/engine.go b/security/authorization/engine/engine.go index 970c560af722..3a95e5ec8800 100644 --- a/security/authorization/engine/engine.go +++ b/security/authorization/engine/engine.go @@ -53,12 +53,12 @@ var intAttributeMap = map[string]func(*AuthorizationArgs) (int, error){ // activationImpl is an implementation of interpreter.Activation. // An Activation is the primary mechanism by which a caller supplies input into a CEL program. type activationImpl struct { - dict map[string]interface{} + dict map[string]any } // ResolveName returns a value from the activation by qualified name, or false if the name // could not be found. -func (activation activationImpl) ResolveName(name string) (interface{}, bool) { +func (activation activationImpl) ResolveName(name string) (any, bool) { result, ok := activation.dict[name] return result, ok } @@ -79,7 +79,7 @@ type AuthorizationArgs struct { // newActivation converts AuthorizationArgs into the activation for CEL. func newActivation(args *AuthorizationArgs) interpreter.Activation { // Fill out evaluation map, only adding the attributes that can be extracted. - evalMap := make(map[string]interface{}) + evalMap := make(map[string]any) for key, function := range stringAttributeMap { val, err := function(args) if err == nil { diff --git a/security/authorization/engine/engine_test.go b/security/authorization/engine/engine_test.go index 1fcff698aa2b..181c2564ba15 100644 --- a/security/authorization/engine/engine_test.go +++ b/security/authorization/engine/engine_test.go @@ -45,19 +45,19 @@ type fakeProgram struct { err error } -func (fake fakeProgram) Eval(vars interface{}) (ref.Val, *cel.EvalDetails, error) { +func (fake fakeProgram) Eval(vars any) (ref.Val, *cel.EvalDetails, error) { return fake.out, nil, fake.err } -func (fake fakeProgram) ContextEval(ctx context.Context, vars interface{}) (ref.Val, *cel.EvalDetails, error) { +func (fake fakeProgram) ContextEval(ctx context.Context, vars any) (ref.Val, *cel.EvalDetails, error) { return fake.Eval(vars) } type valMock struct { - val interface{} + val any } -func (mock valMock) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { +func (mock valMock) ConvertToNative(typeDesc reflect.Type) (any, error) { return nil, nil } @@ -76,7 +76,7 @@ func (mock valMock) Type() ref.Type { return nil } -func (mock valMock) Value() interface{} { +func (mock valMock) Value() any { return mock.val } diff --git a/security/authorization/engine/util_test.go b/security/authorization/engine/util_test.go index e766fbf3ffe0..d991b7a3833d 100644 --- a/security/authorization/engine/util_test.go +++ b/security/authorization/engine/util_test.go @@ -43,44 +43,44 @@ func (s) TestStringConvert(t *testing.T) { wantParsingError bool wantEvalError bool expr string - authzArgs map[string]interface{} + authzArgs map[string]any }{ { desc: "single primitive match", wantEvalOutcome: true, expr: "request.url_path.startsWith('/pkg.service/test')", - authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test"}, + authzArgs: map[string]any{"request.url_path": "/pkg.service/test"}, }, { desc: "single compare match", wantEvalOutcome: true, expr: "connection.uri_san_peer_certificate == 'cluster/ns/default/sa/admin'", - authzArgs: map[string]interface{}{"connection.uri_san_peer_certificate": "cluster/ns/default/sa/admin"}, + authzArgs: map[string]any{"connection.uri_san_peer_certificate": "cluster/ns/default/sa/admin"}, }, { desc: "single primitive no match", wantEvalOutcome: false, expr: "request.url_path.startsWith('/pkg.service/test')", - authzArgs: map[string]interface{}{"request.url_path": "/source/pkg.service/test"}, + authzArgs: map[string]any{"request.url_path": "/source/pkg.service/test"}, }, { desc: "primitive and compare match", wantEvalOutcome: true, expr: "request.url_path == '/pkg.service/test' && connection.uri_san_peer_certificate == 'cluster/ns/default/sa/admin'", - authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test", + authzArgs: map[string]any{"request.url_path": "/pkg.service/test", "connection.uri_san_peer_certificate": "cluster/ns/default/sa/admin"}, }, { desc: "parse error field not present in environment", wantParsingError: true, expr: "request.source_path.startsWith('/pkg.service/test')", - authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test"}, + authzArgs: map[string]any{"request.url_path": "/pkg.service/test"}, }, { desc: "eval error argument not included in environment", wantEvalError: true, expr: "request.url_path.startsWith('/pkg.service/test')", - authzArgs: map[string]interface{}{"request.source_path": "/pkg.service/test"}, + authzArgs: map[string]any{"request.source_path": "/pkg.service/test"}, }, } { test := test diff --git a/security/authorization/go.mod b/security/authorization/go.mod index f15589897ebc..ec4ab2d11d87 100644 --- a/security/authorization/go.mod +++ b/security/authorization/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/security/authorization -go 1.17 +go 1.19 require ( github.com/envoyproxy/go-control-plane v0.11.1 diff --git a/server.go b/server.go index 01b3265223c6..7ec70fda4caa 100644 --- a/server.go +++ b/server.go @@ -86,7 +86,7 @@ func init() { var statusOK = status.New(codes.OK, "") var logger = grpclog.Component("core") -type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error) +type methodHandler func(srv any, ctx context.Context, dec func(any) error, interceptor UnaryServerInterceptor) (any, error) // MethodDesc represents an RPC service's method specification. type MethodDesc struct { @@ -99,20 +99,20 @@ type ServiceDesc struct { ServiceName string // The pointer to the service interface. Used to check whether the user // provided implementation satisfies the interface requirements. - HandlerType interface{} + HandlerType any Methods []MethodDesc Streams []StreamDesc - Metadata interface{} + Metadata any } // serviceInfo wraps information about a service. It is very similar to // ServiceDesc and is constructed from it for internal purposes. type serviceInfo struct { // Contains the implementation for the methods in this service. - serviceImpl interface{} + serviceImpl any methods map[string]*MethodDesc streams map[string]*StreamDesc - mdata interface{} + mdata any } type serverWorkerData struct { @@ -670,7 +670,7 @@ func NewServer(opt ...ServerOption) *Server { // printf records an event in s's event log, unless s has been stopped. // REQUIRES s.mu is held. -func (s *Server) printf(format string, a ...interface{}) { +func (s *Server) printf(format string, a ...any) { if s.events != nil { s.events.Printf(format, a...) } @@ -678,7 +678,7 @@ func (s *Server) printf(format string, a ...interface{}) { // errorf records an error in s's event log, unless s has been stopped. // REQUIRES s.mu is held. -func (s *Server) errorf(format string, a ...interface{}) { +func (s *Server) errorf(format string, a ...any) { if s.events != nil { s.events.Errorf(format, a...) } @@ -693,14 +693,14 @@ type ServiceRegistrar interface { // once the server has started serving. // desc describes the service and its methods and handlers. impl is the // service implementation which is passed to the method handlers. - RegisterService(desc *ServiceDesc, impl interface{}) + RegisterService(desc *ServiceDesc, impl any) } // RegisterService registers a service and its implementation to the gRPC // server. It is called from the IDL generated code. This must be called before // invoking Serve. If ss is non-nil (for legacy code), its type is checked to // ensure it implements sd.HandlerType. -func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { +func (s *Server) RegisterService(sd *ServiceDesc, ss any) { if ss != nil { ht := reflect.TypeOf(sd.HandlerType).Elem() st := reflect.TypeOf(ss) @@ -711,7 +711,7 @@ func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { s.register(sd, ss) } -func (s *Server) register(sd *ServiceDesc, ss interface{}) { +func (s *Server) register(sd *ServiceDesc, ss any) { s.mu.Lock() defer s.mu.Unlock() s.printf("RegisterService(%q)", sd.ServiceName) @@ -752,7 +752,7 @@ type MethodInfo struct { type ServiceInfo struct { Methods []MethodInfo // Metadata is the metadata specified in ServiceDesc when registering service. - Metadata interface{} + Metadata any } // GetServiceInfo returns a map from service names to ServiceInfo. @@ -1135,7 +1135,7 @@ func (s *Server) incrCallsFailed() { atomic.AddInt64(&s.czData.callsFailed, 1) } -func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { +func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg any, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { data, err := encode(s.getCodec(stream.ContentSubtype()), msg) if err != nil { channelz.Error(logger, s.channelzID, "grpc: server failed to encode response: ", err) @@ -1182,7 +1182,7 @@ func chainUnaryServerInterceptors(s *Server) { } func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (any, error) { return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler)) } } @@ -1191,7 +1191,7 @@ func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info if curr == len(interceptors)-1 { return finalHandler } - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler)) } } @@ -1228,7 +1228,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. defer func() { if trInfo != nil { if err != nil && err != io.EOF { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) trInfo.tr.SetError() } trInfo.tr.Finish() @@ -1345,7 +1345,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. if channelz.IsOn() { t.IncrMsgRecv() } - df := func(v interface{}) error { + df := func(v any) error { if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil { return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) } @@ -1509,7 +1509,7 @@ func chainStreamServerInterceptors(s *Server) { } func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor { - return func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { + return func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler)) } } @@ -1518,7 +1518,7 @@ func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, inf if curr == len(interceptors)-1 { return finalHandler } - return func(srv interface{}, stream ServerStream) error { + return func(srv any, stream ServerStream) error { return interceptors[curr+1](srv, stream, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler)) } } @@ -1559,7 +1559,7 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp if trInfo != nil { ss.mu.Lock() if err != nil && err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) ss.trInfo.tr.SetError() } ss.trInfo.tr.Finish() @@ -1662,7 +1662,7 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp trInfo.tr.LazyLog(&trInfo.firstLine, false) } var appErr error - var server interface{} + var server any if info != nil { server = info.serviceImpl } @@ -1728,13 +1728,13 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str pos := strings.LastIndex(sm, "/") if pos == -1 { if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true) + trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []any{sm}}, true) trInfo.tr.SetError() } errDesc := fmt.Sprintf("malformed method name: %q", stream.Method()) if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) trInfo.tr.SetError() } channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err) @@ -1775,7 +1775,7 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str } if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) trInfo.tr.SetError() } channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err) diff --git a/server_test.go b/server_test.go index 85a8f5bf72eb..0048a0f74156 100644 --- a/server_test.go +++ b/server_test.go @@ -32,7 +32,7 @@ import ( "google.golang.org/grpc/status" ) -type emptyServiceServer interface{} +type emptyServiceServer any type testServer struct{} @@ -133,24 +133,24 @@ func (s) TestGetServiceInfo(t *testing.T) { func (s) TestRetryChainedInterceptor(t *testing.T) { var records []int - i1 := func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) { + i1 := func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) { records = append(records, 1) // call handler twice to simulate a retry here. handler(ctx, req) return handler(ctx, req) } - i2 := func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) { + i2 := func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) { records = append(records, 2) return handler(ctx, req) } - i3 := func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) { + i3 := func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) { records = append(records, 3) return handler(ctx, req) } ii := chainUnaryInterceptors([]UnaryServerInterceptor{i1, i2, i3}) - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { return nil, nil } ii(context.Background(), nil, nil, handler) @@ -176,8 +176,8 @@ func BenchmarkChainUnaryInterceptor(b *testing.B) { interceptors := make([]UnaryServerInterceptor, 0, n) for i := 0; i < n; i++ { interceptors = append(interceptors, func( - ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler, - ) (interface{}, error) { + ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler, + ) (any, error) { return handler(ctx, req) }) } @@ -187,7 +187,7 @@ func BenchmarkChainUnaryInterceptor(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := s.opts.unaryInt(context.Background(), nil, nil, - func(ctx context.Context, req interface{}) (interface{}, error) { + func(ctx context.Context, req any) (any, error) { return nil, nil }, ); err != nil { @@ -205,7 +205,7 @@ func BenchmarkChainStreamInterceptor(b *testing.B) { interceptors := make([]StreamServerInterceptor, 0, n) for i := 0; i < n; i++ { interceptors = append(interceptors, func( - srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler, + srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler, ) error { return handler(srv, ss) }) @@ -215,7 +215,7 @@ func BenchmarkChainStreamInterceptor(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - if err := s.opts.streamInt(nil, nil, nil, func(srv interface{}, stream ServerStream) error { + if err := s.opts.streamInt(nil, nil, nil, func(srv any, stream ServerStream) error { return nil }); err != nil { b.Fatal(err) diff --git a/shared_buffer_pool.go b/shared_buffer_pool.go index c3a5a9ac1f19..48a64cfe8e25 100644 --- a/shared_buffer_pool.go +++ b/shared_buffer_pool.go @@ -109,7 +109,7 @@ const ( type simpleSharedBufferChildPool interface { Get(size int) []byte - Put(interface{}) + Put(any) } type bufferPool struct { @@ -133,7 +133,7 @@ func (p *bufferPool) Get(size int) []byte { func newBytesPool(size int) simpleSharedBufferChildPool { return &bufferPool{ Pool: sync.Pool{ - New: func() interface{} { + New: func() any { bs := make([]byte, size) return &bs }, diff --git a/stats/opencensus/go.mod b/stats/opencensus/go.mod index 6fff538fe32e..9f79073d36df 100644 --- a/stats/opencensus/go.mod +++ b/stats/opencensus/go.mod @@ -1,6 +1,6 @@ module google.golang.org/grpc/stats/opencensus -go 1.17 +go 1.19 require ( github.com/google/go-cmp v0.5.9 diff --git a/stats/opencensus/opencensus.go b/stats/opencensus/opencensus.go index 8bebb21575e1..f477d0918a37 100644 --- a/stats/opencensus/opencensus.go +++ b/stats/opencensus/opencensus.go @@ -116,7 +116,7 @@ func perCallTracesAndMetrics(err error, span *trace.Span, startTime time.Time, m // unaryInterceptor handles per RPC context management. It also handles per RPC // tracing and stats by creating a top level call span and recording the latency // for the full RPC call. -func (csh *clientStatsHandler) unaryInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { +func (csh *clientStatsHandler) unaryInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { startTime := time.Now() ctx, span := csh.createCallSpan(ctx, method) err := invoker(ctx, method, req, reply, cc, opts...) diff --git a/stats/stats.go b/stats/stats.go index f23b6b3385bc..4ab70e2d462a 100644 --- a/stats/stats.go +++ b/stats/stats.go @@ -74,7 +74,7 @@ type InPayload struct { // Client is true if this InPayload is from client side. Client bool // Payload is the payload with original type. - Payload interface{} + Payload any // Data is the serialized message payload. Data []byte @@ -144,7 +144,7 @@ type OutPayload struct { // Client is true if this OutPayload is from client side. Client bool // Payload is the payload with original type. - Payload interface{} + Payload any // Data is the serialized message payload. Data []byte // Length is the size of the uncompressed payload data. Does not include any diff --git a/stats/stats_test.go b/stats/stats_test.go index b0b3df70c9d3..7dcb53491a26 100644 --- a/stats/stats_test.go +++ b/stats/stats_test.go @@ -424,7 +424,7 @@ type expectedData struct { type gotData struct { ctx context.Context client bool - s interface{} // This could be RPCStats or ConnStats. + s any // This could be RPCStats or ConnStats. } const ( diff --git a/status/status.go b/status/status.go index bcf2e4d81beb..0d40c5f0810d 100644 --- a/status/status.go +++ b/status/status.go @@ -50,7 +50,7 @@ func New(c codes.Code, msg string) *Status { } // Newf returns New(c, fmt.Sprintf(format, a...)). -func Newf(c codes.Code, format string, a ...interface{}) *Status { +func Newf(c codes.Code, format string, a ...any) *Status { return New(c, fmt.Sprintf(format, a...)) } @@ -60,7 +60,7 @@ func Error(c codes.Code, msg string) error { } // Errorf returns Error(c, fmt.Sprintf(format, a...)). -func Errorf(c codes.Code, format string, a ...interface{}) error { +func Errorf(c codes.Code, format string, a ...any) error { return Error(c, fmt.Sprintf(format, a...)) } diff --git a/status/status_test.go b/status/status_test.go index 216d18bb27b9..d21a862f3637 100644 --- a/status/status_test.go +++ b/status/status_test.go @@ -377,7 +377,7 @@ func (s) TestStatus_WithDetails_Fail(t *testing.T) { func (s) TestStatus_ErrorDetails_Fail(t *testing.T) { tests := []struct { s *Status - i []interface{} + i []any }{ { nil, @@ -389,7 +389,7 @@ func (s) TestStatus_ErrorDetails_Fail(t *testing.T) { }, { New(codes.OK, ""), - []interface{}{}, + []any{}, }, { FromProto(&spb.Status{ @@ -406,7 +406,7 @@ func (s) TestStatus_ErrorDetails_Fail(t *testing.T) { }), }, }), - []interface{}{ + []any{ errors.New(`message type url "" is invalid`), &epb.ResourceInfo{ ResourceType: "book", diff --git a/stream.go b/stream.go index e3bb3f20f389..d7fb37c986b8 100644 --- a/stream.go +++ b/stream.go @@ -55,7 +55,7 @@ import ( // status package, or be one of the context errors. Otherwise, gRPC will use // codes.Unknown as the status code and err.Error() as the status message of the // RPC. -type StreamHandler func(srv interface{}, stream ServerStream) error +type StreamHandler func(srv any, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. Used // on the server when registering services and on the client when initiating @@ -80,9 +80,9 @@ type Stream interface { // Deprecated: See ClientStream and ServerStream documentation instead. Context() context.Context // Deprecated: See ClientStream and ServerStream documentation instead. - SendMsg(m interface{}) error + SendMsg(m any) error // Deprecated: See ClientStream and ServerStream documentation instead. - RecvMsg(m interface{}) error + RecvMsg(m any) error } // ClientStream defines the client-side behavior of a streaming RPC. @@ -127,7 +127,7 @@ type ClientStream interface { // // It is not safe to modify the message after calling SendMsg. Tracing // libraries and stats handlers may use the message lazily. - SendMsg(m interface{}) error + SendMsg(m any) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC @@ -136,7 +136,7 @@ type ClientStream interface { // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m interface{}) error + RecvMsg(m any) error } // NewStream creates a new Stream for the client side. This is typically @@ -861,7 +861,7 @@ func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error cs.buffer = append(cs.buffer, op) } -func (cs *clientStream) SendMsg(m interface{}) (err error) { +func (cs *clientStream) SendMsg(m any) (err error) { defer func() { if err != nil && err != io.EOF { // Call finish on the client stream for errors generated by this SendMsg @@ -905,7 +905,7 @@ func (cs *clientStream) SendMsg(m interface{}) (err error) { return err } -func (cs *clientStream) RecvMsg(m interface{}) error { +func (cs *clientStream) RecvMsg(m any) error { if len(cs.binlogs) != 0 && !cs.serverHeaderBinlogged { // Call Header() to binary log header if it's not already logged. cs.Header() @@ -1029,7 +1029,7 @@ func (cs *clientStream) finish(err error) { cs.cancel() } -func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error { +func (a *csAttempt) sendMsg(m any, hdr, payld, data []byte) error { cs := a.cs if a.trInfo != nil { a.mu.Lock() @@ -1056,7 +1056,7 @@ func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error { return nil } -func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) { +func (a *csAttempt) recvMsg(m any, payInfo *payloadInfo) (err error) { cs := a.cs if len(a.statsHandlers) != 0 && payInfo == nil { payInfo = &payloadInfo{} @@ -1349,7 +1349,7 @@ func (as *addrConnStream) Context() context.Context { return as.s.Context() } -func (as *addrConnStream) SendMsg(m interface{}) (err error) { +func (as *addrConnStream) SendMsg(m any) (err error) { defer func() { if err != nil && err != io.EOF { // Call finish on the client stream for errors generated by this SendMsg @@ -1394,7 +1394,7 @@ func (as *addrConnStream) SendMsg(m interface{}) (err error) { return nil } -func (as *addrConnStream) RecvMsg(m interface{}) (err error) { +func (as *addrConnStream) RecvMsg(m any) (err error) { defer func() { if err != nil || !as.desc.ServerStreams { // err != nil or non-server-streaming indicates end of stream. @@ -1513,7 +1513,7 @@ type ServerStream interface { // // It is not safe to modify the message after calling SendMsg. Tracing // libraries and stats handlers may use the message lazily. - SendMsg(m interface{}) error + SendMsg(m any) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the client has performed a CloseSend. On // any non-EOF error, the stream is aborted and the error contains the @@ -1522,7 +1522,7 @@ type ServerStream interface { // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m interface{}) error + RecvMsg(m any) error } // serverStream implements a server side Stream. @@ -1603,7 +1603,7 @@ func (ss *serverStream) SetTrailer(md metadata.MD) { ss.s.SetTrailer(md) } -func (ss *serverStream) SendMsg(m interface{}) (err error) { +func (ss *serverStream) SendMsg(m any) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() @@ -1611,7 +1611,7 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) } else { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) ss.trInfo.tr.SetError() } } @@ -1678,7 +1678,7 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { return nil } -func (ss *serverStream) RecvMsg(m interface{}) (err error) { +func (ss *serverStream) RecvMsg(m any) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() @@ -1686,7 +1686,7 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } else if err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) + ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) ss.trInfo.tr.SetError() } } @@ -1758,7 +1758,7 @@ func MethodFromServerStream(stream ServerStream) (string, bool) { // prepareMsg returns the hdr, payload and data // using the compressors passed or using the // passed preparedmsg -func prepareMsg(m interface{}, codec baseCodec, cp Compressor, comp encoding.Compressor) (hdr, payload, data []byte, err error) { +func prepareMsg(m any, codec baseCodec, cp Compressor, comp encoding.Compressor) (hdr, payload, data []byte, err error) { if preparedMsg, ok := m.(*PreparedMsg); ok { return preparedMsg.hdr, preparedMsg.payload, preparedMsg.encodedData, nil } diff --git a/test/balancer_test.go b/test/balancer_test.go index df82f8b81115..0c71da7146d6 100644 --- a/test/balancer_test.go +++ b/test/balancer_test.go @@ -284,7 +284,7 @@ const loadMDKey = "X-Endpoint-Load-Metrics-Bin" type testLoadParser struct{} -func (*testLoadParser) Parse(md metadata.MD) interface{} { +func (*testLoadParser) Parse(md metadata.MD) any { vs := md.Get(loadMDKey) if len(vs) == 0 { return nil @@ -975,7 +975,7 @@ type testProducerBuilder struct { ctxChan chan context.Context } -func (b *testProducerBuilder) Build(cci interface{}) (balancer.Producer, func()) { +func (b *testProducerBuilder) Build(cci any) (balancer.Producer, func()) { c := testgrpc.NewTestServiceClient(cci.(grpc.ClientConnInterface)) // Perform the RPC in a goroutine instead of during build because the // subchannel's mutex is held here. diff --git a/test/clientconn_state_transition_test.go b/test/clientconn_state_transition_test.go index 48527d57c0ba..00660168f1b5 100644 --- a/test/clientconn_state_transition_test.go +++ b/test/clientconn_state_transition_test.go @@ -555,7 +555,7 @@ type funcConnectivityStateSubscriber struct { onMsg func(connectivity.State) } -func (f *funcConnectivityStateSubscriber) OnMessage(msg interface{}) { +func (f *funcConnectivityStateSubscriber) OnMessage(msg any) { f.onMsg(msg.(connectivity.State)) } diff --git a/test/end2end_test.go b/test/end2end_test.go index a04289fcfcb3..5e70acdd767b 100644 --- a/test/end2end_test.go +++ b/test/end2end_test.go @@ -3698,7 +3698,7 @@ func (s) TestUnaryClientInterceptor(t *testing.T) { } } -func failOkayRPC(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { +func failOkayRPC(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { err := invoker(ctx, method, req, reply, cc, opts...) if err == nil { return status.Error(codes.NotFound, "") @@ -3769,7 +3769,7 @@ func (s) TestUnaryServerInterceptor(t *testing.T) { } } -func errInjector(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func errInjector(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { return nil, status.Error(codes.PermissionDenied, "") } @@ -3797,7 +3797,7 @@ func (s) TestStreamServerInterceptor(t *testing.T) { } } -func fullDuplexOnly(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func fullDuplexOnly(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if info.FullMethod == "/grpc.testing.TestService/FullDuplexCall" { return handler(srv, ss) } @@ -4877,14 +4877,14 @@ type errCodec struct { noError bool } -func (c *errCodec) Marshal(v interface{}) ([]byte, error) { +func (c *errCodec) Marshal(v any) ([]byte, error) { if c.noError { return []byte{}, nil } return nil, fmt.Errorf("3987^12 + 4365^12 = 4472^12") } -func (c *errCodec) Unmarshal(data []byte, v interface{}) error { +func (c *errCodec) Unmarshal(data []byte, v any) error { return nil } @@ -4897,7 +4897,7 @@ type countingProtoCodec struct { unmarshalCount int32 } -func (p *countingProtoCodec) Marshal(v interface{}) ([]byte, error) { +func (p *countingProtoCodec) Marshal(v any) ([]byte, error) { atomic.AddInt32(&p.marshalCount, 1) vv, ok := v.(proto.Message) if !ok { @@ -4906,7 +4906,7 @@ func (p *countingProtoCodec) Marshal(v interface{}) ([]byte, error) { return proto.Marshal(vv) } -func (p *countingProtoCodec) Unmarshal(data []byte, v interface{}) error { +func (p *countingProtoCodec) Unmarshal(data []byte, v any) error { atomic.AddInt32(&p.unmarshalCount, 1) vv, ok := v.(proto.Message) if !ok { @@ -5028,7 +5028,7 @@ func (s) TestMethodFromServerStream(t *testing.T) { te := newTest(t, e) var method string var ok bool - te.unknownHandler = func(srv interface{}, stream grpc.ServerStream) error { + te.unknownHandler = func(srv any, stream grpc.ServerStream) error { method, ok = grpc.MethodFromServerStream(stream) return nil } @@ -5086,7 +5086,7 @@ func (s) TestInterceptorCanAccessCallOptions(t *testing.T) { } } - te.unaryClientInt = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + te.unaryClientInt = func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { populateOpts(opts) return nil } @@ -5973,7 +5973,7 @@ func (s) TestClientSettingsFloodCloseConn(t *testing.T) { timer.Stop() } -func unaryInterceptorVerifyConn(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func unaryInterceptorVerifyConn(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { conn := transport.GetConnection(ctx) if conn == nil { return nil, status.Error(codes.NotFound, "connection was not in context") @@ -5998,7 +5998,7 @@ func (s) TestUnaryServerInterceptorGetsConnection(t *testing.T) { } } -func streamingInterceptorVerifyConn(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func streamingInterceptorVerifyConn(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { conn := transport.GetConnection(ss.Context()) if conn == nil { return status.Error(codes.NotFound, "connection was not in context") @@ -6030,7 +6030,7 @@ func (s) TestStreamingServerInterceptorGetsConnection(t *testing.T) { // unaryInterceptorVerifyAuthority verifies there is an unambiguous :authority // once the request gets to an interceptor. An unambiguous :authority is defined // as at most a single :authority header, and no host header according to A41. -func unaryInterceptorVerifyAuthority(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func unaryInterceptorVerifyAuthority(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, status.Error(codes.NotFound, "metadata was not in context") diff --git a/test/healthcheck_test.go b/test/healthcheck_test.go index eb343f5a1a7b..c5a16d00ae76 100644 --- a/test/healthcheck_test.go +++ b/test/healthcheck_test.go @@ -121,7 +121,7 @@ func (s *testHealthServer) SetServingStatus(service string, status healthpb.Heal func setupHealthCheckWrapper() (hcEnterChan chan struct{}, hcExitChan chan struct{}, wrapper internal.HealthChecker) { hcEnterChan = make(chan struct{}) hcExitChan = make(chan struct{}) - wrapper = func(ctx context.Context, newStream func(string) (interface{}, error), update func(connectivity.State, error), service string) error { + wrapper = func(ctx context.Context, newStream func(string) (any, error), update func(connectivity.State, error), service string) error { close(hcEnterChan) defer close(hcExitChan) return testHealthCheckFunc(ctx, newStream, update, service) @@ -1122,7 +1122,7 @@ func (s) TestUnknownHandler(t *testing.T) { // An example unknownHandler that returns a different code and a different // method, making sure that we do not expose what methods are implemented to // a client that is not authenticated. - unknownHandler := func(srv interface{}, stream grpc.ServerStream) error { + unknownHandler := func(srv any, stream grpc.ServerStream) error { return status.Error(codes.Unauthenticated, "user unauthenticated") } for _, e := range listTestEnv() { diff --git a/test/interceptor_test.go b/test/interceptor_test.go index c2004bb85465..f6db1d282a4c 100644 --- a/test/interceptor_test.go +++ b/test/interceptor_test.go @@ -49,7 +49,7 @@ const ( // RPC call. func (s) TestUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { errCh := testutils.NewChannel() - unaryInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + unaryInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.Send(fmt.Errorf("unaryInt got %q in context.Val, want %q", got, parentCtxVal)) } @@ -86,7 +86,7 @@ func (s) TestUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { // as well as the ones specified by prior interceptors in the chain. func (s) TestChainUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { errCh := testutils.NewChannel() - firstInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + firstInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.SendContext(ctx, fmt.Errorf("first interceptor got %q in context.Val, want %q", got, parentCtxVal)) } @@ -100,7 +100,7 @@ func (s) TestChainUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { return invoker(firstCtx, method, req, reply, cc, opts...) } - secondInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + secondInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.SendContext(ctx, fmt.Errorf("second interceptor got %q in context.Val, want %q", got, parentCtxVal)) } @@ -114,7 +114,7 @@ func (s) TestChainUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { return invoker(secondCtx, method, req, reply, cc, opts...) } - lastInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + lastInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.SendContext(ctx, fmt.Errorf("last interceptor got %q in context.Val, want %q", got, parentCtxVal)) } @@ -158,7 +158,7 @@ func (s) TestChainUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { // specified by interceptors in the chain. func (s) TestChainOnBaseUnaryClientInterceptor_ContextValuePropagation(t *testing.T) { errCh := testutils.NewChannel() - baseInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + baseInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.SendContext(ctx, fmt.Errorf("base interceptor got %q in context.Val, want %q", got, parentCtxVal)) } @@ -169,7 +169,7 @@ func (s) TestChainOnBaseUnaryClientInterceptor_ContextValuePropagation(t *testin return invoker(baseCtx, method, req, reply, cc, opts...) } - chainInt := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + chainInt := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if got, ok := ctx.Value(parentCtxkey{}).(string); !ok || got != parentCtxVal { errCh.SendContext(ctx, fmt.Errorf("chain interceptor got %q in context.Val, want %q", got, parentCtxVal)) } diff --git a/test/server_test.go b/test/server_test.go index 6d525f7954e1..eb0872d0c113 100644 --- a/test/server_test.go +++ b/test/server_test.go @@ -75,7 +75,7 @@ func (s) TestChainUnaryServerInterceptor(t *testing.T) { secondIntKey = ctxKey("secondIntKey") ) - firstInt := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + firstInt := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if ctx.Value(firstIntKey) != nil { return nil, status.Errorf(codes.Internal, "first interceptor should not have %v in context", firstIntKey) } @@ -101,7 +101,7 @@ func (s) TestChainUnaryServerInterceptor(t *testing.T) { }, nil } - secondInt := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + secondInt := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if ctx.Value(firstIntKey) == nil { return nil, status.Errorf(codes.Internal, "second interceptor should have %v in context", firstIntKey) } @@ -127,7 +127,7 @@ func (s) TestChainUnaryServerInterceptor(t *testing.T) { }, nil } - lastInt := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + lastInt := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if ctx.Value(firstIntKey) == nil { return nil, status.Errorf(codes.Internal, "last interceptor should have %v in context", firstIntKey) } @@ -189,7 +189,7 @@ func (s) TestChainUnaryServerInterceptor(t *testing.T) { func (s) TestChainOnBaseUnaryServerInterceptor(t *testing.T) { baseIntKey := ctxKey("baseIntKey") - baseInt := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + baseInt := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if ctx.Value(baseIntKey) != nil { return nil, status.Errorf(codes.Internal, "base interceptor should not have %v in context", baseIntKey) } @@ -198,7 +198,7 @@ func (s) TestChainOnBaseUnaryServerInterceptor(t *testing.T) { return handler(baseCtx, req) } - chainInt := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + chainInt := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if ctx.Value(baseIntKey) == nil { return nil, status.Errorf(codes.Internal, "chain interceptor should have %v in context", baseIntKey) } @@ -232,7 +232,7 @@ func (s) TestChainOnBaseUnaryServerInterceptor(t *testing.T) { func (s) TestChainStreamServerInterceptor(t *testing.T) { callCounts := make([]int, 4) - firstInt := func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + firstInt := func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if callCounts[0] != 0 { return status.Errorf(codes.Internal, "callCounts[0] should be 0, but got=%d", callCounts[0]) } @@ -249,7 +249,7 @@ func (s) TestChainStreamServerInterceptor(t *testing.T) { return handler(srv, stream) } - secondInt := func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + secondInt := func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if callCounts[0] != 1 { return status.Errorf(codes.Internal, "callCounts[0] should be 1, but got=%d", callCounts[0]) } @@ -266,7 +266,7 @@ func (s) TestChainStreamServerInterceptor(t *testing.T) { return handler(srv, stream) } - lastInt := func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + lastInt := func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if callCounts[0] != 1 { return status.Errorf(codes.Internal, "callCounts[0] should be 1, but got=%d", callCounts[0]) } diff --git a/test/tools/go.mod b/test/tools/go.mod index 06f55734c49a..33856e80e68a 100644 --- a/test/tools/go.mod +++ b/test/tools/go.mod @@ -1,14 +1,19 @@ module google.golang.org/grpc/test/tools -go 1.14 +go 1.19 require ( - github.com/BurntSushi/toml v1.3.2 // indirect github.com/client9/misspell v0.3.4 github.com/golang/protobuf v1.5.3 - golang.org/x/exp/typeparams v0.0.0-20230713183714-613f0c0eb8a1 // indirect golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 golang.org/x/tools v0.11.0 - google.golang.org/protobuf v1.31.0 // indirect honnef.co/go/tools v0.4.3 ) + +require ( + github.com/BurntSushi/toml v1.3.2 // indirect + golang.org/x/exp/typeparams v0.0.0-20230713183714-613f0c0eb8a1 // indirect + golang.org/x/mod v0.12.0 // indirect + golang.org/x/sys v0.10.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect +) diff --git a/test/tools/go.sum b/test/tools/go.sum index f1705b0530cf..f8b2d644b624 100644 --- a/test/tools/go.sum +++ b/test/tools/go.sum @@ -1,4 +1,3 @@ -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI= @@ -8,68 +7,27 @@ github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= -golang.org/x/exp/typeparams v0.0.0-20221208152030-732eee02a75a/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/exp/typeparams v0.0.0-20230713183714-613f0c0eb8a1 h1:VXDua8UTGWl3e7L5kCk5Vyt0LA3QpsyRu6XXL7K3v1w= golang.org/x/exp/typeparams v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.4.1-0.20221208213631-3f74d914ae6d/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.11.0 h1:EMCa6U9S2LtZXLAMoWiR/R8dAQFRqbAitmbJ2UKhoi8= golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/test/xds/xds_server_rbac_test.go b/test/xds/xds_server_rbac_test.go index 914b59db31c6..fa684104281b 100644 --- a/test/xds/xds_server_rbac_test.go +++ b/test/xds/xds_server_rbac_test.go @@ -446,7 +446,7 @@ func (s) TestRBACHTTPFilter(t *testing.T) { { AuditLogger: &v3corepb.TypedExtensionConfig{ Name: "stat_logger", - TypedConfig: createXDSTypedStruct(t, map[string]interface{}{}, "stat_logger"), + TypedConfig: createXDSTypedStruct(t, map[string]any{}, "stat_logger"), }, IsOptional: false, }, @@ -975,7 +975,7 @@ func (*loggerBuilder) ParseLoggerConfig(config json.RawMessage) (audit.LoggerCon const typeURLPrefix = "grpc.authz.audit_logging/" // Builds custom configs for audit logger RBAC protos. -func createXDSTypedStruct(t *testing.T, in map[string]interface{}, name string) *anypb.Any { +func createXDSTypedStruct(t *testing.T, in map[string]any, name string) *anypb.Any { t.Helper() pb, err := structpb.NewStruct(in) if err != nil { diff --git a/trace.go b/trace.go index 07a2d26b3e77..9ded79321ba7 100644 --- a/trace.go +++ b/trace.go @@ -97,8 +97,8 @@ func truncate(x string, l int) string { // payload represents an RPC request or response payload. type payload struct { - sent bool // whether this is an outgoing payload - msg interface{} // e.g. a proto.Message + sent bool // whether this is an outgoing payload + msg any // e.g. a proto.Message // TODO(dsymonds): add stringifying info to codec, and limit how much we hold here? } @@ -111,7 +111,7 @@ func (p payload) String() string { type fmtStringer struct { format string - a []interface{} + a []any } func (f *fmtStringer) String() string { diff --git a/vet.sh b/vet.sh index 920e8263fb49..ad0cc96b08e7 100755 --- a/vet.sh +++ b/vet.sh @@ -84,6 +84,9 @@ not git grep -l 'x/net/context' -- "*.go" # thread safety. git grep -l '"math/rand"' -- "*.go" 2>&1 | not grep -v '^examples\|^stress\|grpcrand\|^benchmark\|wrr_test' +# - Do not use "interface{}"; use "any" instead. +git grep -l 'interface{}' -- "*.go" 2>&1 | not grep -v 'pb\.go$\|protoc-gen-go-grpc' + # - Do not call grpclog directly. Use grpclog.Component instead. git grep -l -e 'grpclog.I' --or -e 'grpclog.W' --or -e 'grpclog.E' --or -e 'grpclog.F' --or -e 'grpclog.V' -- "*.go" | not grep -v '^grpclog/component.go\|^internal/grpctest/tlogger_test.go' diff --git a/xds/internal/balancer/cdsbalancer/cdsbalancer_security_test.go b/xds/internal/balancer/cdsbalancer/cdsbalancer_security_test.go index fcd2e26960c0..64e18c21b6b1 100644 --- a/xds/internal/balancer/cdsbalancer/cdsbalancer_security_test.go +++ b/xds/internal/balancer/cdsbalancer/cdsbalancer_security_test.go @@ -98,7 +98,7 @@ type fakeProviderBuilder struct { name string } -func (b *fakeProviderBuilder) ParseConfig(config interface{}) (*certprovider.BuildableConfig, error) { +func (b *fakeProviderBuilder) ParseConfig(config any) (*certprovider.BuildableConfig, error) { s, ok := config.(string) if !ok { return nil, fmt.Errorf("providerBuilder %s received config of type %T, want string", b.name, config) diff --git a/xds/internal/balancer/clusterresolver/resource_resolver.go b/xds/internal/balancer/clusterresolver/resource_resolver.go index d696e67a872c..aaababa71c57 100644 --- a/xds/internal/balancer/clusterresolver/resource_resolver.go +++ b/xds/internal/balancer/clusterresolver/resource_resolver.go @@ -52,7 +52,7 @@ type endpointsResolver interface { // The second return result indicates whether the resolver was able to // successfully resolve the resource name to endpoints. If set to false, the // first return result is invalid and must not be used. - lastUpdate() (interface{}, bool) + lastUpdate() (any, bool) // resolverNow triggers re-resolution of the resource. resolveNow() diff --git a/xds/internal/balancer/clusterresolver/resource_resolver_dns.go b/xds/internal/balancer/clusterresolver/resource_resolver_dns.go index 756251012f6c..9052190b0ff0 100644 --- a/xds/internal/balancer/clusterresolver/resource_resolver_dns.go +++ b/xds/internal/balancer/clusterresolver/resource_resolver_dns.go @@ -96,7 +96,7 @@ func newDNSResolver(target string, topLevelResolver topLevelResolver, logger *gr return ret } -func (dr *dnsDiscoveryMechanism) lastUpdate() (interface{}, bool) { +func (dr *dnsDiscoveryMechanism) lastUpdate() (any, bool) { dr.mu.Lock() defer dr.mu.Unlock() diff --git a/xds/internal/balancer/clusterresolver/resource_resolver_eds.go b/xds/internal/balancer/clusterresolver/resource_resolver_eds.go index 86af73cbae21..3d0ec356e93a 100644 --- a/xds/internal/balancer/clusterresolver/resource_resolver_eds.go +++ b/xds/internal/balancer/clusterresolver/resource_resolver_eds.go @@ -37,7 +37,7 @@ type edsDiscoveryMechanism struct { update *xdsresource.EndpointsUpdate // Nil indicates no update received so far. } -func (er *edsDiscoveryMechanism) lastUpdate() (interface{}, bool) { +func (er *edsDiscoveryMechanism) lastUpdate() (any, bool) { er.mu.Lock() defer er.mu.Unlock() diff --git a/xds/internal/balancer/wrrlocality/balancer.go b/xds/internal/balancer/wrrlocality/balancer.go index 7886d2253581..943ee7806ba1 100644 --- a/xds/internal/balancer/wrrlocality/balancer.go +++ b/xds/internal/balancer/wrrlocality/balancer.go @@ -103,7 +103,7 @@ func (bb) ParseConfig(s json.RawMessage) (serviceconfig.LoadBalancingConfig, err type attributeKey struct{} // Equal allows the values to be compared by Attributes.Equal. -func (a AddrInfo) Equal(o interface{}) bool { +func (a AddrInfo) Equal(o any) bool { oa, ok := o.(AddrInfo) return ok && oa.LocalityWeight == a.LocalityWeight } diff --git a/xds/internal/clusterspecifier/cluster_specifier.go b/xds/internal/clusterspecifier/cluster_specifier.go index b95a101116ed..8fcb83cdbb1e 100644 --- a/xds/internal/clusterspecifier/cluster_specifier.go +++ b/xds/internal/clusterspecifier/cluster_specifier.go @@ -26,7 +26,7 @@ import ( // BalancerConfig is the Go Native JSON representation of a balancer // configuration. -type BalancerConfig []map[string]interface{} +type BalancerConfig []map[string]any // ClusterSpecifier defines the parsing functionality of a Cluster Specifier. type ClusterSpecifier interface { diff --git a/xds/internal/clusterspecifier/rls/rls_test.go b/xds/internal/clusterspecifier/rls/rls_test.go index 9e0a10b648e6..0be52f4db406 100644 --- a/xds/internal/clusterspecifier/rls/rls_test.go +++ b/xds/internal/clusterspecifier/rls/rls_test.go @@ -80,13 +80,13 @@ func (s) TestParseClusterSpecifierConfig(t *testing.T) { if test.wantErr { // Successfully received an error. return } - // Marshal and then unmarshal into interface{} to get rid of - // nondeterministic protojson Marshaling. + // Marshal and then unmarshal into any to get rid of nondeterministic + // protojson Marshaling. lbCfgJSON, err := json.Marshal(lbCfg) if err != nil { t.Fatalf("json.Marshal(%+v) returned err %v", lbCfg, err) } - var got interface{} + var got any err = json.Unmarshal(lbCfgJSON, got) if err != nil { t.Fatalf("json.Unmarshal(%+v) returned err %v", lbCfgJSON, err) @@ -95,7 +95,7 @@ func (s) TestParseClusterSpecifierConfig(t *testing.T) { if err != nil { t.Fatalf("json.Marshal(%+v) returned err %v", test.wantConfig, err) } - var want interface{} + var want any err = json.Unmarshal(wantCfgJSON, want) if err != nil { t.Fatalf("json.Unmarshal(%+v) returned err %v", lbCfgJSON, err) diff --git a/xds/internal/httpfilter/fault/fault.go b/xds/internal/httpfilter/fault/fault.go index 725b50a76a83..aa329d13ac30 100644 --- a/xds/internal/httpfilter/fault/fault.go +++ b/xds/internal/httpfilter/fault/fault.go @@ -297,5 +297,5 @@ func (*okStream) Header() (metadata.MD, error) { return nil, nil } func (*okStream) Trailer() metadata.MD { return nil } func (*okStream) CloseSend() error { return nil } func (o *okStream) Context() context.Context { return o.ctx } -func (*okStream) SendMsg(m interface{}) error { return io.EOF } -func (*okStream) RecvMsg(m interface{}) error { return io.EOF } +func (*okStream) SendMsg(m any) error { return io.EOF } +func (*okStream) RecvMsg(m any) error { return io.EOF } diff --git a/xds/internal/internal.go b/xds/internal/internal.go index ba6fa3d78807..fda4c7f56106 100644 --- a/xds/internal/internal.go +++ b/xds/internal/internal.go @@ -47,7 +47,7 @@ func (l LocalityID) ToString() (string, error) { } // Equal allows the values to be compared by Attributes.Equal. -func (l LocalityID) Equal(o interface{}) bool { +func (l LocalityID) Equal(o any) bool { ol, ok := o.(LocalityID) if !ok { return false @@ -82,4 +82,4 @@ func SetLocalityID(addr resolver.Address, l LocalityID) resolver.Address { } // ResourceTypeMapForTesting maps TypeUrl to corresponding ResourceType. -var ResourceTypeMapForTesting map[string]interface{} +var ResourceTypeMapForTesting map[string]any diff --git a/xds/internal/resolver/cluster_specifier_plugin_test.go b/xds/internal/resolver/cluster_specifier_plugin_test.go index 2a01beaeebc6..38ab9acf5b9f 100644 --- a/xds/internal/resolver/cluster_specifier_plugin_test.go +++ b/xds/internal/resolver/cluster_specifier_plugin_test.go @@ -96,15 +96,15 @@ func (testClusterSpecifierPlugin) ParseClusterSpecifierConfig(cfg proto.Message) if cfg == nil { return nil, fmt.Errorf("testClusterSpecifierPlugin: nil configuration message provided") } - any, ok := cfg.(*anypb.Any) + anyp, ok := cfg.(*anypb.Any) if !ok { return nil, fmt.Errorf("testClusterSpecifierPlugin: error parsing config %v: got type %T, want *anypb.Any", cfg, cfg) } lbCfg := new(wrapperspb.StringValue) - if err := ptypes.UnmarshalAny(any, lbCfg); err != nil { + if err := ptypes.UnmarshalAny(anyp, lbCfg); err != nil { return nil, fmt.Errorf("testClusterSpecifierPlugin: error parsing config %v: %v", cfg, err) } - return []map[string]interface{}{{"csp_experimental": cspBalancerConfig{ArbitraryField: lbCfg.GetValue()}}}, nil + return []map[string]any{{"csp_experimental": cspBalancerConfig{ArbitraryField: lbCfg.GetValue()}}}, nil } // TestResolverClusterSpecifierPlugin tests the case where a route configuration diff --git a/xds/internal/resolver/serviceconfig.go b/xds/internal/resolver/serviceconfig.go index 913f6b3ae7c9..02470ddca5e4 100644 --- a/xds/internal/resolver/serviceconfig.go +++ b/xds/internal/resolver/serviceconfig.go @@ -53,10 +53,10 @@ type serviceConfig struct { LoadBalancingConfig balancerConfig `json:"loadBalancingConfig"` } -type balancerConfig []map[string]interface{} +type balancerConfig []map[string]any -func newBalancerConfig(name string, config interface{}) balancerConfig { - return []map[string]interface{}{{name: config}} +func newBalancerConfig(name string, config any) balancerConfig { + return []map[string]any{{name: config}} } type cdsBalancerConfig struct { diff --git a/xds/internal/xdsclient/bootstrap/bootstrap_test.go b/xds/internal/xdsclient/bootstrap/bootstrap_test.go index 026460458b08..d9eb786bbe11 100644 --- a/xds/internal/xdsclient/bootstrap/bootstrap_test.go +++ b/xds/internal/xdsclient/bootstrap/bootstrap_test.go @@ -508,7 +508,7 @@ type fakeCertProviderBuilder struct{} // ParseConfig expects input in JSON format containing a map from string to // string, with a single entry and mapKey being "configKey". -func (b *fakeCertProviderBuilder) ParseConfig(cfg interface{}) (*certprovider.BuildableConfig, error) { +func (b *fakeCertProviderBuilder) ParseConfig(cfg any) (*certprovider.BuildableConfig, error) { config, ok := cfg.(json.RawMessage) if !ok { return nil, fmt.Errorf("fakeCertProviderBuilder received config of type %T, want []byte", config) diff --git a/xds/internal/xdsclient/load/store.go b/xds/internal/xdsclient/load/store.go index 551a5147b6bd..1f266ae20185 100644 --- a/xds/internal/xdsclient/load/store.go +++ b/xds/internal/xdsclient/load/store.go @@ -277,7 +277,7 @@ func (ls *perClusterStore) stats() *Data { } sd := newData(ls.cluster, ls.service) - ls.drops.Range(func(key, val interface{}) bool { + ls.drops.Range(func(key, val any) bool { d := atomic.SwapUint64(val.(*uint64), 0) if d == 0 { return true @@ -291,7 +291,7 @@ func (ls *perClusterStore) stats() *Data { } return true }) - ls.localityRPCCount.Range(func(key, val interface{}) bool { + ls.localityRPCCount.Range(func(key, val any) bool { countData := val.(*rpcCountData) succeeded := countData.loadAndClearSucceeded() inProgress := countData.loadInProgress() @@ -308,7 +308,7 @@ func (ls *perClusterStore) stats() *Data { }, LoadStats: make(map[string]ServerLoadData), } - countData.serverLoads.Range(func(key, val interface{}) bool { + countData.serverLoads.Range(func(key, val any) bool { sum, count := val.(*rpcLoadData).loadAndClear() if count == 0 { return true diff --git a/xds/internal/xdsclient/xdslbregistry/xdslbregistry_test.go b/xds/internal/xdsclient/xdslbregistry/xdslbregistry_test.go index f1ce5496b794..ad5a99b7b86d 100644 --- a/xds/internal/xdsclient/xdslbregistry/xdslbregistry_test.go +++ b/xds/internal/xdsclient/xdslbregistry/xdslbregistry_test.go @@ -307,11 +307,11 @@ func (s) TestConvertToServiceConfigSuccess(t *testing.T) { } // got and want must be unmarshalled since JSON strings shouldn't // generally be directly compared. - var got []map[string]interface{} + var got []map[string]any if err := json.Unmarshal(rawJSON, &got); err != nil { t.Fatalf("Error unmarshalling rawJSON (%q): %v", rawJSON, err) } - var want []map[string]interface{} + var want []map[string]any if err := json.Unmarshal(json.RawMessage(test.wantConfig), &want); err != nil { t.Fatalf("Error unmarshalling wantConfig (%q): %v", test.wantConfig, err) } @@ -322,7 +322,7 @@ func (s) TestConvertToServiceConfigSuccess(t *testing.T) { } } -func jsonMarshal(t *testing.T, x interface{}) string { +func jsonMarshal(t *testing.T, x any) string { t.Helper() js, err := json.Marshal(x) if err != nil { diff --git a/xds/internal/xdsclient/xdsresource/errors.go b/xds/internal/xdsclient/xdsresource/errors.go index 00ef9310481a..7bac4469b78b 100644 --- a/xds/internal/xdsclient/xdsresource/errors.go +++ b/xds/internal/xdsclient/xdsresource/errors.go @@ -53,7 +53,7 @@ func (e *xdsClientError) Error() string { // NewErrorf creates an xds client error. The callbacks are called with this // error, to pass additional information about the error. -func NewErrorf(t ErrorType, format string, args ...interface{}) error { +func NewErrorf(t ErrorType, format string, args ...any) error { return &xdsClientError{t: t, desc: fmt.Sprintf(format, args...)} } diff --git a/xds/internal/xdsclient/xdsresource/resource_type.go b/xds/internal/xdsclient/xdsresource/resource_type.go index f67f0ea15325..7cd64201dae1 100644 --- a/xds/internal/xdsclient/xdsresource/resource_type.go +++ b/xds/internal/xdsclient/xdsresource/resource_type.go @@ -32,7 +32,7 @@ import ( ) func init() { - internal.ResourceTypeMapForTesting = make(map[string]interface{}) + internal.ResourceTypeMapForTesting = make(map[string]any) internal.ResourceTypeMapForTesting[version.V3ListenerURL] = listenerType internal.ResourceTypeMapForTesting[version.V3RouteConfigURL] = routeConfigType internal.ResourceTypeMapForTesting[version.V3ClusterURL] = clusterType diff --git a/xds/internal/xdsclient/xdsresource/type.go b/xds/internal/xdsclient/xdsresource/type.go index 0fb3f274ed46..35cfa9ee7678 100644 --- a/xds/internal/xdsclient/xdsresource/type.go +++ b/xds/internal/xdsclient/xdsresource/type.go @@ -30,7 +30,7 @@ import ( // context/logic available at the xdsClient layer. Since these validation are // performed on internal update structs, they can be shared between different // API clients. -type UpdateValidatorFunc func(interface{}) error +type UpdateValidatorFunc func(any) error // UpdateMetadata contains the metadata for each update, including timestamp, // raw message, and so on. diff --git a/xds/internal/xdsclient/xdsresource/unmarshal_cds_test.go b/xds/internal/xdsclient/xdsresource/unmarshal_cds_test.go index 67f0f7896b26..dd01b09b7c3b 100644 --- a/xds/internal/xdsclient/xdsresource/unmarshal_cds_test.go +++ b/xds/internal/xdsclient/xdsresource/unmarshal_cds_test.go @@ -1545,11 +1545,11 @@ func (s) TestValidateClusterWithOutlierDetection(t *testing.T) { } // got and want must be unmarshalled since JSON strings shouldn't // generally be directly compared. - var got map[string]interface{} + var got map[string]any if err := json.Unmarshal(update.OutlierDetection, &got); err != nil { t.Fatalf("Error unmarshalling update.OutlierDetection (%q): %v", update.OutlierDetection, err) } - var want map[string]interface{} + var want map[string]any if err := json.Unmarshal(json.RawMessage(test.wantODCfg), &want); err != nil { t.Fatalf("Error unmarshalling wantODCfg (%q): %v", test.wantODCfg, err) } diff --git a/xds/internal/xdsclient/xdsresource/unmarshal_rds_test.go b/xds/internal/xdsclient/xdsresource/unmarshal_rds_test.go index fa10d2aa2694..6435237a3572 100644 --- a/xds/internal/xdsclient/xdsresource/unmarshal_rds_test.go +++ b/xds/internal/xdsclient/xdsresource/unmarshal_rds_test.go @@ -785,7 +785,7 @@ func (mockClusterSpecifierPlugin) TypeURLs() []string { } func (mockClusterSpecifierPlugin) ParseClusterSpecifierConfig(proto.Message) (clusterspecifier.BalancerConfig, error) { - return []map[string]interface{}{}, nil + return []map[string]any{}, nil } type errorClusterSpecifierPlugin struct{} diff --git a/xds/server.go b/xds/server.go index f005f2a79365..fe2138c8bc24 100644 --- a/xds/server.go +++ b/xds/server.go @@ -63,7 +63,7 @@ var ( // grpcServer contains methods from grpc.Server which are used by the // GRPCServer type here. This is useful for overriding in unit tests. type grpcServer interface { - RegisterService(*grpc.ServiceDesc, interface{}) + RegisterService(*grpc.ServiceDesc, any) Serve(net.Listener) error Stop() GracefulStop() @@ -191,7 +191,7 @@ func (s *GRPCServer) loggingServerModeChangeCallback(addr net.Addr, args Serving // RegisterService registers a service and its implementation to the underlying // gRPC server. It is called from the IDL generated code. This must be called // before invoking Serve. -func (s *GRPCServer) RegisterService(sd *grpc.ServiceDesc, ss interface{}) { +func (s *GRPCServer) RegisterService(sd *grpc.ServiceDesc, ss any) { s.gs.RegisterService(sd, ss) } @@ -394,7 +394,7 @@ func routeAndProcess(ctx context.Context) error { // xdsUnaryInterceptor is the unary interceptor added to the gRPC server to // perform any xDS specific functionality on unary RPCs. -func xdsUnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { +func xdsUnaryInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { if envconfig.XDSRBAC { if err := routeAndProcess(ctx); err != nil { return nil, err @@ -405,7 +405,7 @@ func xdsUnaryInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServ // xdsStreamInterceptor is the stream interceptor added to the gRPC server to // perform any xDS specific functionality on streaming RPCs. -func xdsStreamInterceptor(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func xdsStreamInterceptor(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if envconfig.XDSRBAC { if err := routeAndProcess(ss.Context()); err != nil { return err diff --git a/xds/server_test.go b/xds/server_test.go index acaed78b913d..2830143f2dee 100644 --- a/xds/server_test.go +++ b/xds/server_test.go @@ -71,7 +71,7 @@ type fakeGRPCServer struct { serveCh *testutils.Channel } -func (f *fakeGRPCServer) RegisterService(*grpc.ServiceDesc, interface{}) { +func (f *fakeGRPCServer) RegisterService(*grpc.ServiceDesc, any) { f.registerServiceCh.Send(nil) } @@ -312,7 +312,7 @@ type fakeProviderBuilder struct { buildCh *testutils.Channel } -func (b *fakeProviderBuilder) ParseConfig(cfg interface{}) (*certprovider.BuildableConfig, error) { +func (b *fakeProviderBuilder) ParseConfig(cfg any) (*certprovider.BuildableConfig, error) { var config string if err := json.Unmarshal(cfg.(json.RawMessage), &config); err != nil { return nil, fmt.Errorf("providerBuilder %s failed to unmarshal config: %v", b.name, cfg)