From 02cd07d9bb5609fe76f8bb8d948037e79a8b29c7 Mon Sep 17 00:00:00 2001 From: Doug Fawley Date: Tue, 29 Sep 2020 15:17:06 -0700 Subject: [PATCH] cmd/protoc-gen-go-grpc: revert to interface-based service registration (#3911) --- .../grpc_lb_v1/load_balancer_grpc.pb.go | 102 ++--- balancer/grpclb/grpclb_test.go | 8 +- .../proto/grpc_lookup_v1/rls_grpc.pb.go | 100 ++--- balancer/roundrobin/roundrobin_test.go | 13 +- benchmark/benchmark.go | 23 +- benchmark/grpc_testing/services_grpc.pb.go | 361 ++++++++-------- benchmark/worker/main.go | 14 +- binarylog/binarylog_end2end_test.go | 18 +- channelz/grpc_channelz_v1/channelz_grpc.pb.go | 321 ++++++-------- cmd/protoc-gen-go-grpc/README.md | 117 +----- cmd/protoc-gen-go-grpc/grpc.go | 382 ++++++----------- cmd/protoc-gen-go-grpc/main.go | 6 +- .../proto/grpc_gcp/handshaker_grpc.pb.go | 109 ++--- .../meshca/internal/v1/meshca_grpc.pb.go | 102 ++--- .../features/authentication/server/main.go | 8 +- examples/features/cancellation/server/main.go | 8 +- examples/features/compression/server/main.go | 8 +- examples/features/deadline/server/main.go | 8 +- examples/features/debugging/server/main.go | 24 +- .../features/encryption/ALTS/server/main.go | 10 +- .../features/encryption/TLS/server/main.go | 8 +- examples/features/errors/server/main.go | 4 +- examples/features/health/server/main.go | 10 +- examples/features/interceptor/server/main.go | 15 +- examples/features/keepalive/server/main.go | 9 +- .../features/load_balancing/server/main.go | 4 +- examples/features/metadata/server/main.go | 19 +- examples/features/multiplex/server/main.go | 22 +- .../features/name_resolving/server/main.go | 11 +- examples/features/profiling/README.md | 2 +- examples/features/profiling/server/main.go | 8 +- examples/features/proto/echo/echo_grpc.pb.go | 177 ++++---- examples/features/reflection/server/main.go | 20 +- examples/features/retry/server/main.go | 3 +- examples/features/wait_for_ready/main.go | 9 +- examples/features/xds/server/main.go | 5 +- examples/gotutorial.md | 8 +- examples/helloworld/greeter_server/main.go | 11 +- .../helloworld/helloworld_grpc.pb.go | 74 ++-- .../routeguide/route_guide_grpc.pb.go | 177 ++++---- examples/route_guide/server/server.go | 12 +- health/grpc_health_v1/health_grpc.pb.go | 151 +++---- interop/alts/server/server.go | 2 +- interop/grpc_testing/test_grpc.pb.go | 394 +++++++++--------- interop/server/server.go | 2 +- interop/test_utils.go | 16 +- interop/xds/client/client.go | 8 +- interop/xds/server/server.go | 10 +- profiling/proto/service_grpc.pb.go | 136 +++--- .../reflection_grpc.pb.go | 103 ++--- reflection/grpc_testing/test_grpc.pb.go | 109 +++-- reflection/serverreflection_test.go | 11 +- regenerate.sh | 37 +- .../advancedtls_integration_test.go | 8 +- stats/grpc_testing/test_grpc.pb.go | 185 ++++---- stats/stats_test.go | 25 +- stress/client/main.go | 11 +- stress/grpc_testing/metrics_grpc.pb.go | 128 +++--- test/balancer_test.go | 26 +- test/channelz_linux_go110_test.go | 2 +- test/channelz_test.go | 40 +- test/creds_test.go | 20 +- test/end2end_test.go | 321 +++++++------- test/goaway_test.go | 2 +- test/gracefulstop_test.go | 2 +- test/grpc_testing/test_grpc.pb.go | 245 +++++------ test/healthcheck_test.go | 2 +- test/local_creds_test.go | 4 +- 68 files changed, 1908 insertions(+), 2442 deletions(-) diff --git a/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go b/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go index ecbb77509ea..b28b7341dba 100644 --- a/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go +++ b/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go @@ -29,14 +29,8 @@ func NewLoadBalancerClient(cc grpc.ClientConnInterface) LoadBalancerClient { return &loadBalancerClient{cc} } -var loadBalancerBalanceLoadStreamDesc = &grpc.StreamDesc{ - StreamName: "BalanceLoad", - ServerStreams: true, - ClientStreams: true, -} - func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) { - stream, err := c.cc.NewStream(ctx, loadBalancerBalanceLoadStreamDesc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) + stream, err := c.cc.NewStream(ctx, &_LoadBalancer_serviceDesc.Streams[0], "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) if err != nil { return nil, err } @@ -66,17 +60,35 @@ func (x *loadBalancerBalanceLoadClient) Recv() (*LoadBalanceResponse, error) { return m, nil } -// LoadBalancerService is the service API for LoadBalancer service. -// Fields should be assigned to their respective handler implementations only before -// RegisterLoadBalancerService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type LoadBalancerService struct { +// LoadBalancerServer is the server API for LoadBalancer service. +// All implementations should embed UnimplementedLoadBalancerServer +// for forward compatibility +type LoadBalancerServer interface { // Bidirectional rpc to get a list of servers. - BalanceLoad func(LoadBalancer_BalanceLoadServer) error + BalanceLoad(LoadBalancer_BalanceLoadServer) error } -func (s *LoadBalancerService) balanceLoad(_ interface{}, stream grpc.ServerStream) error { - return s.BalanceLoad(&loadBalancerBalanceLoadServer{stream}) +// UnimplementedLoadBalancerServer should be embedded to have forward compatible implementations. +type UnimplementedLoadBalancerServer struct { +} + +func (UnimplementedLoadBalancerServer) BalanceLoad(LoadBalancer_BalanceLoadServer) error { + return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented") +} + +// UnsafeLoadBalancerServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LoadBalancerServer will +// result in compilation errors. +type UnsafeLoadBalancerServer interface { + mustEmbedUnimplementedLoadBalancerServer() +} + +func RegisterLoadBalancerServer(s *grpc.Server, srv LoadBalancerServer) { + s.RegisterService(&_LoadBalancer_serviceDesc, srv) +} + +func _LoadBalancer_BalanceLoad_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(LoadBalancerServer).BalanceLoad(&loadBalancerBalanceLoadServer{stream}) } type LoadBalancer_BalanceLoadServer interface { @@ -101,53 +113,17 @@ func (x *loadBalancerBalanceLoadServer) Recv() (*LoadBalanceRequest, error) { return m, nil } -// RegisterLoadBalancerService registers a service implementation with a gRPC server. -func RegisterLoadBalancerService(s grpc.ServiceRegistrar, srv *LoadBalancerService) { - srvCopy := *srv - if srvCopy.BalanceLoad == nil { - srvCopy.BalanceLoad = func(LoadBalancer_BalanceLoadServer) error { - return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.lb.v1.LoadBalancer", - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "BalanceLoad", - Handler: srvCopy.balanceLoad, - ServerStreams: true, - ClientStreams: true, - }, +var _LoadBalancer_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.lb.v1.LoadBalancer", + HandlerType: (*LoadBalancerServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "BalanceLoad", + Handler: _LoadBalancer_BalanceLoad_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "grpc/lb/v1/load_balancer.proto", - } - - s.RegisterService(&sd, nil) -} - -// LoadBalancerServer is the service API for LoadBalancer service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type LoadBalancerServer interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(LoadBalancer_BalanceLoadServer) error -} - -// UnimplementedLoadBalancerServer can be embedded to have forward compatible implementations of -// LoadBalancerServer -type UnimplementedLoadBalancerServer struct { -} - -func (UnimplementedLoadBalancerServer) BalanceLoad(LoadBalancer_BalanceLoadServer) error { - return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented") -} - -// RegisterLoadBalancerServer registers a service implementation with a gRPC server. -func RegisterLoadBalancerServer(s grpc.ServiceRegistrar, srv LoadBalancerServer) { - str := &LoadBalancerService{ - BalanceLoad: srv.BalanceLoad, - } - RegisterLoadBalancerService(s, str) + }, + Metadata: "grpc/lb/v1/load_balancer.proto", } diff --git a/balancer/grpclb/grpclb_test.go b/balancer/grpclb/grpclb_test.go index 5a2297d43ec..48082e2069f 100644 --- a/balancer/grpclb/grpclb_test.go +++ b/balancer/grpclb/grpclb_test.go @@ -276,6 +276,8 @@ func (b *remoteBalancer) BalanceLoad(stream lbgrpc.LoadBalancer_BalanceLoadServe } type testServer struct { + testpb.UnimplementedTestServiceServer + addr string fallback bool } @@ -304,11 +306,7 @@ func startBackends(sn string, fallback bool, lis ...net.Listener) (servers []*gr sn: sn, } s := grpc.NewServer(grpc.Creds(creds)) - ts := &testServer{addr: l.Addr().String(), fallback: fallback} - testpb.RegisterTestServiceService(s, &testpb.TestServiceService{ - EmptyCall: ts.EmptyCall, - FullDuplexCall: ts.FullDuplexCall, - }) + testpb.RegisterTestServiceServer(s, &testServer{addr: l.Addr().String(), fallback: fallback}) servers = append(servers, s) go func(s *grpc.Server, l net.Listener) { s.Serve(l) diff --git a/balancer/rls/internal/proto/grpc_lookup_v1/rls_grpc.pb.go b/balancer/rls/internal/proto/grpc_lookup_v1/rls_grpc.pb.go index 93c95132b52..f3147189337 100644 --- a/balancer/rls/internal/proto/grpc_lookup_v1/rls_grpc.pb.go +++ b/balancer/rls/internal/proto/grpc_lookup_v1/rls_grpc.pb.go @@ -29,10 +29,6 @@ func NewRouteLookupServiceClient(cc grpc.ClientConnInterface) RouteLookupService return &routeLookupServiceClient{cc} } -var routeLookupServiceRouteLookupStreamDesc = &grpc.StreamDesc{ - StreamName: "RouteLookup", -} - func (c *routeLookupServiceClient) RouteLookup(ctx context.Context, in *RouteLookupRequest, opts ...grpc.CallOption) (*RouteLookupResponse, error) { out := new(RouteLookupResponse) err := c.cc.Invoke(ctx, "/grpc.lookup.v1.RouteLookupService/RouteLookup", in, out, opts...) @@ -42,78 +38,62 @@ func (c *routeLookupServiceClient) RouteLookup(ctx context.Context, in *RouteLoo return out, nil } -// RouteLookupServiceService is the service API for RouteLookupService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterRouteLookupServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type RouteLookupServiceService struct { +// RouteLookupServiceServer is the server API for RouteLookupService service. +// All implementations must embed UnimplementedRouteLookupServiceServer +// for forward compatibility +type RouteLookupServiceServer interface { // Lookup returns a target for a single key. - RouteLookup func(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) + RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) + mustEmbedUnimplementedRouteLookupServiceServer() } -func (s *RouteLookupServiceService) routeLookup(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +// UnimplementedRouteLookupServiceServer must be embedded to have forward compatible implementations. +type UnimplementedRouteLookupServiceServer struct { +} + +func (UnimplementedRouteLookupServiceServer) RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented") +} +func (UnimplementedRouteLookupServiceServer) mustEmbedUnimplementedRouteLookupServiceServer() {} + +// UnsafeRouteLookupServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to RouteLookupServiceServer will +// result in compilation errors. +type UnsafeRouteLookupServiceServer interface { + mustEmbedUnimplementedRouteLookupServiceServer() +} + +func RegisterRouteLookupServiceServer(s *grpc.Server, srv RouteLookupServiceServer) { + s.RegisterService(&_RouteLookupService_serviceDesc, srv) +} + +func _RouteLookupService_RouteLookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RouteLookupRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.RouteLookup(ctx, in) + return srv.(RouteLookupServiceServer).RouteLookup(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.lookup.v1.RouteLookupService/RouteLookup", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.RouteLookup(ctx, req.(*RouteLookupRequest)) + return srv.(RouteLookupServiceServer).RouteLookup(ctx, req.(*RouteLookupRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterRouteLookupServiceService registers a service implementation with a gRPC server. -func RegisterRouteLookupServiceService(s grpc.ServiceRegistrar, srv *RouteLookupServiceService) { - srvCopy := *srv - if srvCopy.RouteLookup == nil { - srvCopy.RouteLookup = func(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.lookup.v1.RouteLookupService", - Methods: []grpc.MethodDesc{ - { - MethodName: "RouteLookup", - Handler: srvCopy.routeLookup, - }, +var _RouteLookupService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.lookup.v1.RouteLookupService", + HandlerType: (*RouteLookupServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "RouteLookup", + Handler: _RouteLookupService_RouteLookup_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc/lookup/v1/rls.proto", - } - - s.RegisterService(&sd, nil) -} - -// RouteLookupServiceServer is the service API for RouteLookupService service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type RouteLookupServiceServer interface { - // Lookup returns a target for a single key. - RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) -} - -// UnimplementedRouteLookupServiceServer can be embedded to have forward compatible implementations of -// RouteLookupServiceServer -type UnimplementedRouteLookupServiceServer struct { -} - -func (UnimplementedRouteLookupServiceServer) RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented") -} - -// RegisterRouteLookupServiceServer registers a service implementation with a gRPC server. -func RegisterRouteLookupServiceServer(s grpc.ServiceRegistrar, srv RouteLookupServiceServer) { - str := &RouteLookupServiceService{ - RouteLookup: srv.RouteLookup, - } - RegisterRouteLookupServiceService(s, str) + }, + Streams: []grpc.StreamDesc{}, + Metadata: "grpc/lookup/v1/rls.proto", } diff --git a/balancer/roundrobin/roundrobin_test.go b/balancer/roundrobin/roundrobin_test.go index 0c54465a6af..5a8ba481c9f 100644 --- a/balancer/roundrobin/roundrobin_test.go +++ b/balancer/roundrobin/roundrobin_test.go @@ -47,11 +47,15 @@ func Test(t *testing.T) { grpctest.RunSubTests(t, s{}) } -func emptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { +type testServer struct { + testpb.UnimplementedTestServiceServer +} + +func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { return &testpb.Empty{}, nil } -func fullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { +func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { return nil } @@ -81,10 +85,7 @@ func startTestServers(count int) (_ *test, err error) { } s := grpc.NewServer() - testpb.RegisterTestServiceService(s, &testpb.TestServiceService{ - EmptyCall: emptyCall, - FullDuplexCall: fullDuplexCall, - }) + testpb.RegisterTestServiceServer(s, &testServer{}) t.servers = append(t.servers, s) t.addresses = append(t.addresses, lis.Addr().String()) diff --git a/benchmark/benchmark.go b/benchmark/benchmark.go index 5794aebcc55..56841e17236 100644 --- a/benchmark/benchmark.go +++ b/benchmark/benchmark.go @@ -61,14 +61,8 @@ func NewPayload(t testpb.PayloadType, size int) *testpb.Payload { return p } -type testServer struct{} - -func (s *testServer) Svc() *testpb.BenchmarkServiceService { - return &testpb.BenchmarkServiceService{ - UnaryCall: s.UnaryCall, - StreamingCall: s.StreamingCall, - UnconstrainedStreamingCall: s.UnconstrainedStreamingCall, - } +type testServer struct { + testpb.UnimplementedBenchmarkServiceServer } func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { @@ -150,17 +144,10 @@ func (s *testServer) UnconstrainedStreamingCall(stream testpb.BenchmarkService_U // byteBufServer is a gRPC server that sends and receives byte buffer. // The purpose is to benchmark the gRPC performance without protobuf serialization/deserialization overhead. type byteBufServer struct { + testpb.UnimplementedBenchmarkServiceServer respSize int32 } -func (s *byteBufServer) Svc() *testpb.BenchmarkServiceService { - return &testpb.BenchmarkServiceService{ - UnaryCall: s.UnaryCall, - StreamingCall: s.StreamingCall, - UnconstrainedStreamingCall: s.UnconstrainedStreamingCall, - } -} - // UnaryCall is an empty function and is not used for benchmark. // If bytebuf UnaryCall benchmark is needed later, the function body needs to be updated. func (s *byteBufServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { @@ -224,13 +211,13 @@ func StartServer(info ServerInfo, opts ...grpc.ServerOption) func() { s := grpc.NewServer(opts...) switch info.Type { case "protobuf": - testpb.RegisterBenchmarkServiceService(s, (&testServer{}).Svc()) + testpb.RegisterBenchmarkServiceServer(s, &testServer{}) case "bytebuf": respSize, ok := info.Metadata.(int32) if !ok { logger.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type) } - testpb.RegisterBenchmarkServiceService(s, (&byteBufServer{respSize: respSize}).Svc()) + testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize}) default: logger.Fatalf("failed to StartServer, unknown Type: %v", info.Type) } diff --git a/benchmark/grpc_testing/services_grpc.pb.go b/benchmark/grpc_testing/services_grpc.pb.go index 81e9ed6a2ac..64937d1e460 100644 --- a/benchmark/grpc_testing/services_grpc.pb.go +++ b/benchmark/grpc_testing/services_grpc.pb.go @@ -36,10 +36,6 @@ func NewBenchmarkServiceClient(cc grpc.ClientConnInterface) BenchmarkServiceClie return &benchmarkServiceClient{cc} } -var benchmarkServiceUnaryCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnaryCall", -} - func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { out := new(SimpleResponse) err := c.cc.Invoke(ctx, "/grpc.testing.BenchmarkService/UnaryCall", in, out, opts...) @@ -49,14 +45,8 @@ func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleReques return out, nil } -var benchmarkServiceStreamingCallStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *benchmarkServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) { - stream, err := c.cc.NewStream(ctx, benchmarkServiceStreamingCallStreamDesc, "/grpc.testing.BenchmarkService/StreamingCall", opts...) + stream, err := c.cc.NewStream(ctx, &_BenchmarkService_serviceDesc.Streams[0], "/grpc.testing.BenchmarkService/StreamingCall", opts...) if err != nil { return nil, err } @@ -86,14 +76,8 @@ func (x *benchmarkServiceStreamingCallClient) Recv() (*SimpleResponse, error) { return m, nil } -var benchmarkServiceUnconstrainedStreamingCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnconstrainedStreamingCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *benchmarkServiceClient) UnconstrainedStreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_UnconstrainedStreamingCallClient, error) { - stream, err := c.cc.NewStream(ctx, benchmarkServiceUnconstrainedStreamingCallStreamDesc, "/grpc.testing.BenchmarkService/UnconstrainedStreamingCall", opts...) + stream, err := c.cc.NewStream(ctx, &_BenchmarkService_serviceDesc.Streams[1], "/grpc.testing.BenchmarkService/UnconstrainedStreamingCall", opts...) if err != nil { return nil, err } @@ -123,44 +107,68 @@ func (x *benchmarkServiceUnconstrainedStreamingCallClient) Recv() (*SimpleRespon return m, nil } -// BenchmarkServiceService is the service API for BenchmarkService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterBenchmarkServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type BenchmarkServiceService struct { +// BenchmarkServiceServer is the server API for BenchmarkService service. +// All implementations must embed UnimplementedBenchmarkServiceServer +// for forward compatibility +type BenchmarkServiceServer interface { // One request followed by one response. // The server returns the client payload as-is. - UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) + UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) // One request followed by one response. // The server returns the client payload as-is. - StreamingCall func(BenchmarkService_StreamingCallServer) error + StreamingCall(BenchmarkService_StreamingCallServer) error // Unconstrainted streaming. // Both server and client keep sending & receiving simultaneously. - UnconstrainedStreamingCall func(BenchmarkService_UnconstrainedStreamingCallServer) error + UnconstrainedStreamingCall(BenchmarkService_UnconstrainedStreamingCallServer) error + mustEmbedUnimplementedBenchmarkServiceServer() +} + +// UnimplementedBenchmarkServiceServer must be embedded to have forward compatible implementations. +type UnimplementedBenchmarkServiceServer struct { +} + +func (UnimplementedBenchmarkServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") +} +func (UnimplementedBenchmarkServiceServer) StreamingCall(BenchmarkService_StreamingCallServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingCall not implemented") +} +func (UnimplementedBenchmarkServiceServer) UnconstrainedStreamingCall(BenchmarkService_UnconstrainedStreamingCallServer) error { + return status.Errorf(codes.Unimplemented, "method UnconstrainedStreamingCall not implemented") } +func (UnimplementedBenchmarkServiceServer) mustEmbedUnimplementedBenchmarkServiceServer() {} -func (s *BenchmarkServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +// UnsafeBenchmarkServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to BenchmarkServiceServer will +// result in compilation errors. +type UnsafeBenchmarkServiceServer interface { + mustEmbedUnimplementedBenchmarkServiceServer() +} + +func RegisterBenchmarkServiceServer(s *grpc.Server, srv BenchmarkServiceServer) { + s.RegisterService(&_BenchmarkService_serviceDesc, srv) +} + +func _BenchmarkService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnaryCall(ctx, in) + return srv.(BenchmarkServiceServer).UnaryCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.BenchmarkService/UnaryCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnaryCall(ctx, req.(*SimpleRequest)) + return srv.(BenchmarkServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) } return interceptor(ctx, in, info, handler) } -func (s *BenchmarkServiceService) streamingCall(_ interface{}, stream grpc.ServerStream) error { - return s.StreamingCall(&benchmarkServiceStreamingCallServer{stream}) -} -func (s *BenchmarkServiceService) unconstrainedStreamingCall(_ interface{}, stream grpc.ServerStream) error { - return s.UnconstrainedStreamingCall(&benchmarkServiceUnconstrainedStreamingCallServer{stream}) + +func _BenchmarkService_StreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(BenchmarkServiceServer).StreamingCall(&benchmarkServiceStreamingCallServer{stream}) } type BenchmarkService_StreamingCallServer interface { @@ -185,6 +193,10 @@ func (x *benchmarkServiceStreamingCallServer) Recv() (*SimpleRequest, error) { return m, nil } +func _BenchmarkService_UnconstrainedStreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(BenchmarkServiceServer).UnconstrainedStreamingCall(&benchmarkServiceUnconstrainedStreamingCallServer{stream}) +} + type BenchmarkService_UnconstrainedStreamingCallServer interface { Send(*SimpleResponse) error Recv() (*SimpleRequest, error) @@ -207,50 +219,30 @@ func (x *benchmarkServiceUnconstrainedStreamingCallServer) Recv() (*SimpleReques return m, nil } -// RegisterBenchmarkServiceService registers a service implementation with a gRPC server. -func RegisterBenchmarkServiceService(s grpc.ServiceRegistrar, srv *BenchmarkServiceService) { - srvCopy := *srv - if srvCopy.UnaryCall == nil { - srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") - } - } - if srvCopy.StreamingCall == nil { - srvCopy.StreamingCall = func(BenchmarkService_StreamingCallServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingCall not implemented") - } - } - if srvCopy.UnconstrainedStreamingCall == nil { - srvCopy.UnconstrainedStreamingCall = func(BenchmarkService_UnconstrainedStreamingCallServer) error { - return status.Errorf(codes.Unimplemented, "method UnconstrainedStreamingCall not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.BenchmarkService", - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: srvCopy.unaryCall, - }, +var _BenchmarkService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.BenchmarkService", + HandlerType: (*BenchmarkServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UnaryCall", + Handler: _BenchmarkService_UnaryCall_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingCall", - Handler: srvCopy.streamingCall, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "UnconstrainedStreamingCall", - Handler: srvCopy.unconstrainedStreamingCall, - ServerStreams: true, - ClientStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "StreamingCall", + Handler: _BenchmarkService_StreamingCall_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "benchmark/grpc_testing/services.proto", - } - - s.RegisterService(&sd, nil) + { + StreamName: "UnconstrainedStreamingCall", + Handler: _BenchmarkService_UnconstrainedStreamingCall_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "benchmark/grpc_testing/services.proto", } // WorkerServiceClient is the client API for WorkerService service. @@ -285,14 +277,8 @@ func NewWorkerServiceClient(cc grpc.ClientConnInterface) WorkerServiceClient { return &workerServiceClient{cc} } -var workerServiceRunServerStreamDesc = &grpc.StreamDesc{ - StreamName: "RunServer", - ServerStreams: true, - ClientStreams: true, -} - func (c *workerServiceClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) { - stream, err := c.cc.NewStream(ctx, workerServiceRunServerStreamDesc, "/grpc.testing.WorkerService/RunServer", opts...) + stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[0], "/grpc.testing.WorkerService/RunServer", opts...) if err != nil { return nil, err } @@ -322,14 +308,8 @@ func (x *workerServiceRunServerClient) Recv() (*ServerStatus, error) { return m, nil } -var workerServiceRunClientStreamDesc = &grpc.StreamDesc{ - StreamName: "RunClient", - ServerStreams: true, - ClientStreams: true, -} - func (c *workerServiceClient) RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) { - stream, err := c.cc.NewStream(ctx, workerServiceRunClientStreamDesc, "/grpc.testing.WorkerService/RunClient", opts...) + stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[1], "/grpc.testing.WorkerService/RunClient", opts...) if err != nil { return nil, err } @@ -359,10 +339,6 @@ func (x *workerServiceRunClientClient) Recv() (*ClientStatus, error) { return m, nil } -var workerServiceCoreCountStreamDesc = &grpc.StreamDesc{ - StreamName: "CoreCount", -} - func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) { out := new(CoreResponse) err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/CoreCount", in, out, opts...) @@ -372,10 +348,6 @@ func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, op return out, nil } -var workerServiceQuitWorkerStreamDesc = &grpc.StreamDesc{ - StreamName: "QuitWorker", -} - func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) { out := new(Void) err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/QuitWorker", in, out, opts...) @@ -385,70 +357,62 @@ func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ... return out, nil } -// WorkerServiceService is the service API for WorkerService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterWorkerServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type WorkerServiceService struct { +// WorkerServiceServer is the server API for WorkerService service. +// All implementations must embed UnimplementedWorkerServiceServer +// for forward compatibility +type WorkerServiceServer interface { // Start server with specified workload. // First request sent specifies the ServerConfig followed by ServerStatus // response. After that, a "Mark" can be sent anytime to request the latest // stats. Closing the stream will initiate shutdown of the test server // and once the shutdown has finished, the OK status is sent to terminate // this RPC. - RunServer func(WorkerService_RunServerServer) error + RunServer(WorkerService_RunServerServer) error // Start client with specified workload. // First request sent specifies the ClientConfig followed by ClientStatus // response. After that, a "Mark" can be sent anytime to request the latest // stats. Closing the stream will initiate shutdown of the test client // and once the shutdown has finished, the OK status is sent to terminate // this RPC. - RunClient func(WorkerService_RunClientServer) error + RunClient(WorkerService_RunClientServer) error // Just return the core count - unary call - CoreCount func(context.Context, *CoreRequest) (*CoreResponse, error) + CoreCount(context.Context, *CoreRequest) (*CoreResponse, error) // Quit this worker - QuitWorker func(context.Context, *Void) (*Void, error) + QuitWorker(context.Context, *Void) (*Void, error) + mustEmbedUnimplementedWorkerServiceServer() } -func (s *WorkerServiceService) runServer(_ interface{}, stream grpc.ServerStream) error { - return s.RunServer(&workerServiceRunServerServer{stream}) +// UnimplementedWorkerServiceServer must be embedded to have forward compatible implementations. +type UnimplementedWorkerServiceServer struct { } -func (s *WorkerServiceService) runClient(_ interface{}, stream grpc.ServerStream) error { - return s.RunClient(&workerServiceRunClientServer{stream}) + +func (UnimplementedWorkerServiceServer) RunServer(WorkerService_RunServerServer) error { + return status.Errorf(codes.Unimplemented, "method RunServer not implemented") } -func (s *WorkerServiceService) coreCount(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CoreRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return s.CoreCount(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: s, - FullMethod: "/grpc.testing.WorkerService/CoreCount", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.CoreCount(ctx, req.(*CoreRequest)) - } - return interceptor(ctx, in, info, handler) +func (UnimplementedWorkerServiceServer) RunClient(WorkerService_RunClientServer) error { + return status.Errorf(codes.Unimplemented, "method RunClient not implemented") } -func (s *WorkerServiceService) quitWorker(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Void) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return s.QuitWorker(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: s, - FullMethod: "/grpc.testing.WorkerService/QuitWorker", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.QuitWorker(ctx, req.(*Void)) - } - return interceptor(ctx, in, info, handler) +func (UnimplementedWorkerServiceServer) CoreCount(context.Context, *CoreRequest) (*CoreResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CoreCount not implemented") +} +func (UnimplementedWorkerServiceServer) QuitWorker(context.Context, *Void) (*Void, error) { + return nil, status.Errorf(codes.Unimplemented, "method QuitWorker not implemented") +} +func (UnimplementedWorkerServiceServer) mustEmbedUnimplementedWorkerServiceServer() {} + +// UnsafeWorkerServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to WorkerServiceServer will +// result in compilation errors. +type UnsafeWorkerServiceServer interface { + mustEmbedUnimplementedWorkerServiceServer() +} + +func RegisterWorkerServiceServer(s *grpc.Server, srv WorkerServiceServer) { + s.RegisterService(&_WorkerService_serviceDesc, srv) +} + +func _WorkerService_RunServer_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(WorkerServiceServer).RunServer(&workerServiceRunServerServer{stream}) } type WorkerService_RunServerServer interface { @@ -473,6 +437,10 @@ func (x *workerServiceRunServerServer) Recv() (*ServerArgs, error) { return m, nil } +func _WorkerService_RunClient_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(WorkerServiceServer).RunClient(&workerServiceRunClientServer{stream}) +} + type WorkerService_RunClientServer interface { Send(*ClientStatus) error Recv() (*ClientArgs, error) @@ -495,57 +463,68 @@ func (x *workerServiceRunClientServer) Recv() (*ClientArgs, error) { return m, nil } -// RegisterWorkerServiceService registers a service implementation with a gRPC server. -func RegisterWorkerServiceService(s grpc.ServiceRegistrar, srv *WorkerServiceService) { - srvCopy := *srv - if srvCopy.RunServer == nil { - srvCopy.RunServer = func(WorkerService_RunServerServer) error { - return status.Errorf(codes.Unimplemented, "method RunServer not implemented") - } +func _WorkerService_CoreCount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CoreRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkerServiceServer).CoreCount(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.testing.WorkerService/CoreCount", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkerServiceServer).CoreCount(ctx, req.(*CoreRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _WorkerService_QuitWorker_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Void) + if err := dec(in); err != nil { + return nil, err } - if srvCopy.RunClient == nil { - srvCopy.RunClient = func(WorkerService_RunClientServer) error { - return status.Errorf(codes.Unimplemented, "method RunClient not implemented") - } + if interceptor == nil { + return srv.(WorkerServiceServer).QuitWorker(ctx, in) } - if srvCopy.CoreCount == nil { - srvCopy.CoreCount = func(context.Context, *CoreRequest) (*CoreResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CoreCount not implemented") - } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.testing.WorkerService/QuitWorker", } - if srvCopy.QuitWorker == nil { - srvCopy.QuitWorker = func(context.Context, *Void) (*Void, error) { - return nil, status.Errorf(codes.Unimplemented, "method QuitWorker not implemented") - } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkerServiceServer).QuitWorker(ctx, req.(*Void)) } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.WorkerService", - Methods: []grpc.MethodDesc{ - { - MethodName: "CoreCount", - Handler: srvCopy.coreCount, - }, - { - MethodName: "QuitWorker", - Handler: srvCopy.quitWorker, - }, + return interceptor(ctx, in, info, handler) +} + +var _WorkerService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.WorkerService", + HandlerType: (*WorkerServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CoreCount", + Handler: _WorkerService_CoreCount_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "RunServer", - Handler: srvCopy.runServer, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "RunClient", - Handler: srvCopy.runClient, - ServerStreams: true, - ClientStreams: true, - }, + { + MethodName: "QuitWorker", + Handler: _WorkerService_QuitWorker_Handler, }, - Metadata: "benchmark/grpc_testing/services.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "RunServer", + Handler: _WorkerService_RunServer_Handler, + ServerStreams: true, + ClientStreams: true, + }, + { + StreamName: "RunClient", + Handler: _WorkerService_RunClient_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "benchmark/grpc_testing/services.proto", } diff --git a/benchmark/worker/main.go b/benchmark/worker/main.go index 71a1fb6d294..634f09e658c 100644 --- a/benchmark/worker/main.go +++ b/benchmark/worker/main.go @@ -75,19 +75,11 @@ func (byteBufCodec) String() string { // workerServer implements WorkerService rpc handlers. // It can create benchmarkServer or benchmarkClient on demand. type workerServer struct { + testpb.UnimplementedWorkerServiceServer stop chan<- bool serverPort int } -func (s *workerServer) Svc() *testpb.WorkerServiceService { - return &testpb.WorkerServiceService{ - RunServer: s.RunServer, - RunClient: s.RunClient, - CoreCount: s.CoreCount, - QuitWorker: s.QuitWorker, - } -} - func (s *workerServer) RunServer(stream testpb.WorkerService_RunServerServer) error { var bs *benchmarkServer defer func() { @@ -217,10 +209,10 @@ func main() { s := grpc.NewServer() stop := make(chan bool) - testpb.RegisterWorkerServiceService(s, (&workerServer{ + testpb.RegisterWorkerServiceServer(s, &workerServer{ stop: stop, serverPort: *serverPort, - }).Svc()) + }) go func() { <-stop diff --git a/binarylog/binarylog_end2end_test.go b/binarylog/binarylog_end2end_test.go index b8caa828a68..89685c65a26 100644 --- a/binarylog/binarylog_end2end_test.go +++ b/binarylog/binarylog_end2end_test.go @@ -115,18 +115,10 @@ var ( ) type testServer struct { + testpb.UnimplementedTestServiceServer te *test } -func (s *testServer) Svc() *testpb.TestServiceService { - return &testpb.TestServiceService{ - UnaryCall: s.UnaryCall, - FullDuplexCall: s.FullDuplexCall, - ClientStreamCall: s.ClientStreamCall, - ServerStreamCall: s.ServerStreamCall, - } -} - func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { md, ok := metadata.FromIncomingContext(ctx) if ok { @@ -224,7 +216,7 @@ func (s *testServer) ServerStreamCall(in *testpb.SimpleRequest, stream testpb.Te type test struct { t *testing.T - testService *testpb.TestServiceService // nil means none + testService testpb.TestServiceServer // nil means none // srv and srvAddr are set once startServer is called. srv *grpc.Server srvAddr string // Server IP without port. @@ -279,7 +271,7 @@ func (lw *listenerWrapper) Accept() (net.Conn, error) { // startServer starts a gRPC server listening. Callers should defer a // call to te.tearDown to clean up. -func (te *test) startServer(ts *testpb.TestServiceService) { +func (te *test) startServer(ts testpb.TestServiceServer) { te.testService = ts lis, err := net.Listen("tcp", "localhost:0") @@ -295,7 +287,7 @@ func (te *test) startServer(ts *testpb.TestServiceService) { s := grpc.NewServer(opts...) te.srv = s if te.testService != nil { - testpb.RegisterTestServiceService(s, te.testService) + testpb.RegisterTestServiceServer(s, te.testService) } go s.Serve(lis) @@ -791,7 +783,7 @@ func (ed *expectedData) toServerLogEntries() []*pb.GrpcLogEntry { func runRPCs(t *testing.T, tc *testConfig, cc *rpcConfig) *expectedData { te := newTest(t, tc) - te.startServer((&testServer{te: te}).Svc()) + te.startServer(&testServer{te: te}) defer te.tearDown() expect := &expectedData{ diff --git a/channelz/grpc_channelz_v1/channelz_grpc.pb.go b/channelz/grpc_channelz_v1/channelz_grpc.pb.go index e56d7353d8f..8fba59abe56 100644 --- a/channelz/grpc_channelz_v1/channelz_grpc.pb.go +++ b/channelz/grpc_channelz_v1/channelz_grpc.pb.go @@ -42,10 +42,6 @@ func NewChannelzClient(cc grpc.ClientConnInterface) ChannelzClient { return &channelzClient{cc} } -var channelzGetTopChannelsStreamDesc = &grpc.StreamDesc{ - StreamName: "GetTopChannels", -} - func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsRequest, opts ...grpc.CallOption) (*GetTopChannelsResponse, error) { out := new(GetTopChannelsResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetTopChannels", in, out, opts...) @@ -55,10 +51,6 @@ func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsR return out, nil } -var channelzGetServersStreamDesc = &grpc.StreamDesc{ - StreamName: "GetServers", -} - func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest, opts ...grpc.CallOption) (*GetServersResponse, error) { out := new(GetServersResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServers", in, out, opts...) @@ -68,10 +60,6 @@ func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest, return out, nil } -var channelzGetServerStreamDesc = &grpc.StreamDesc{ - StreamName: "GetServer", -} - func (c *channelzClient) GetServer(ctx context.Context, in *GetServerRequest, opts ...grpc.CallOption) (*GetServerResponse, error) { out := new(GetServerResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServer", in, out, opts...) @@ -81,10 +69,6 @@ func (c *channelzClient) GetServer(ctx context.Context, in *GetServerRequest, op return out, nil } -var channelzGetServerSocketsStreamDesc = &grpc.StreamDesc{ - StreamName: "GetServerSockets", -} - func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSocketsRequest, opts ...grpc.CallOption) (*GetServerSocketsResponse, error) { out := new(GetServerSocketsResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServerSockets", in, out, opts...) @@ -94,10 +78,6 @@ func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSock return out, nil } -var channelzGetChannelStreamDesc = &grpc.StreamDesc{ - StreamName: "GetChannel", -} - func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) { out := new(GetChannelResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetChannel", in, out, opts...) @@ -107,10 +87,6 @@ func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest, return out, nil } -var channelzGetSubchannelStreamDesc = &grpc.StreamDesc{ - StreamName: "GetSubchannel", -} - func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelRequest, opts ...grpc.CallOption) (*GetSubchannelResponse, error) { out := new(GetSubchannelResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSubchannel", in, out, opts...) @@ -120,10 +96,6 @@ func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelReq return out, nil } -var channelzGetSocketStreamDesc = &grpc.StreamDesc{ - StreamName: "GetSocket", -} - func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, opts ...grpc.CallOption) (*GetSocketResponse, error) { out := new(GetSocketResponse) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSocket", in, out, opts...) @@ -133,284 +105,223 @@ func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, op return out, nil } -// ChannelzService is the service API for Channelz service. -// Fields should be assigned to their respective handler implementations only before -// RegisterChannelzService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type ChannelzService struct { +// ChannelzServer is the server API for Channelz service. +// All implementations should embed UnimplementedChannelzServer +// for forward compatibility +type ChannelzServer interface { // Gets all root channels (i.e. channels the application has directly // created). This does not include subchannels nor non-top level channels. - GetTopChannels func(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) + GetTopChannels(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) // Gets all servers that exist in the process. - GetServers func(context.Context, *GetServersRequest) (*GetServersResponse, error) + GetServers(context.Context, *GetServersRequest) (*GetServersResponse, error) // Returns a single Server, or else a NOT_FOUND code. - GetServer func(context.Context, *GetServerRequest) (*GetServerResponse, error) + GetServer(context.Context, *GetServerRequest) (*GetServerResponse, error) // Gets all server sockets that exist in the process. - GetServerSockets func(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) + GetServerSockets(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) // Returns a single Channel, or else a NOT_FOUND code. - GetChannel func(context.Context, *GetChannelRequest) (*GetChannelResponse, error) + GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) // Returns a single Subchannel, or else a NOT_FOUND code. - GetSubchannel func(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) + GetSubchannel(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) // Returns a single Socket or else a NOT_FOUND code. - GetSocket func(context.Context, *GetSocketRequest) (*GetSocketResponse, error) + GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) +} + +// UnimplementedChannelzServer should be embedded to have forward compatible implementations. +type UnimplementedChannelzServer struct { } -func (s *ChannelzService) getTopChannels(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func (UnimplementedChannelzServer) GetTopChannels(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetTopChannels not implemented") +} +func (UnimplementedChannelzServer) GetServers(context.Context, *GetServersRequest) (*GetServersResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetServers not implemented") +} +func (UnimplementedChannelzServer) GetServer(context.Context, *GetServerRequest) (*GetServerResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetServer not implemented") +} +func (UnimplementedChannelzServer) GetServerSockets(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetServerSockets not implemented") +} +func (UnimplementedChannelzServer) GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetChannel not implemented") +} +func (UnimplementedChannelzServer) GetSubchannel(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetSubchannel not implemented") +} +func (UnimplementedChannelzServer) GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented") +} + +// UnsafeChannelzServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ChannelzServer will +// result in compilation errors. +type UnsafeChannelzServer interface { + mustEmbedUnimplementedChannelzServer() +} + +func RegisterChannelzServer(s *grpc.Server, srv ChannelzServer) { + s.RegisterService(&_Channelz_serviceDesc, srv) +} + +func _Channelz_GetTopChannels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetTopChannelsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetTopChannels(ctx, in) + return srv.(ChannelzServer).GetTopChannels(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetTopChannels", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetTopChannels(ctx, req.(*GetTopChannelsRequest)) + return srv.(ChannelzServer).GetTopChannels(ctx, req.(*GetTopChannelsRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getServers(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetServers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetServersRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetServers(ctx, in) + return srv.(ChannelzServer).GetServers(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetServers", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetServers(ctx, req.(*GetServersRequest)) + return srv.(ChannelzServer).GetServers(ctx, req.(*GetServersRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getServer(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetServerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetServer(ctx, in) + return srv.(ChannelzServer).GetServer(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetServer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetServer(ctx, req.(*GetServerRequest)) + return srv.(ChannelzServer).GetServer(ctx, req.(*GetServerRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getServerSockets(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetServerSockets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetServerSocketsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetServerSockets(ctx, in) + return srv.(ChannelzServer).GetServerSockets(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetServerSockets", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetServerSockets(ctx, req.(*GetServerSocketsRequest)) + return srv.(ChannelzServer).GetServerSockets(ctx, req.(*GetServerSocketsRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getChannel(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetChannelRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetChannel(ctx, in) + return srv.(ChannelzServer).GetChannel(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetChannel", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetChannel(ctx, req.(*GetChannelRequest)) + return srv.(ChannelzServer).GetChannel(ctx, req.(*GetChannelRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getSubchannel(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetSubchannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetSubchannelRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetSubchannel(ctx, in) + return srv.(ChannelzServer).GetSubchannel(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetSubchannel", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetSubchannel(ctx, req.(*GetSubchannelRequest)) + return srv.(ChannelzServer).GetSubchannel(ctx, req.(*GetSubchannelRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ChannelzService) getSocket(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Channelz_GetSocket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetSocketRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetSocket(ctx, in) + return srv.(ChannelzServer).GetSocket(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.channelz.v1.Channelz/GetSocket", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetSocket(ctx, req.(*GetSocketRequest)) + return srv.(ChannelzServer).GetSocket(ctx, req.(*GetSocketRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterChannelzService registers a service implementation with a gRPC server. -func RegisterChannelzService(s grpc.ServiceRegistrar, srv *ChannelzService) { - srvCopy := *srv - if srvCopy.GetTopChannels == nil { - srvCopy.GetTopChannels = func(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetTopChannels not implemented") - } - } - if srvCopy.GetServers == nil { - srvCopy.GetServers = func(context.Context, *GetServersRequest) (*GetServersResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServers not implemented") - } - } - if srvCopy.GetServer == nil { - srvCopy.GetServer = func(context.Context, *GetServerRequest) (*GetServerResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServer not implemented") - } - } - if srvCopy.GetServerSockets == nil { - srvCopy.GetServerSockets = func(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServerSockets not implemented") - } - } - if srvCopy.GetChannel == nil { - srvCopy.GetChannel = func(context.Context, *GetChannelRequest) (*GetChannelResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetChannel not implemented") - } - } - if srvCopy.GetSubchannel == nil { - srvCopy.GetSubchannel = func(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetSubchannel not implemented") - } - } - if srvCopy.GetSocket == nil { - srvCopy.GetSocket = func(context.Context, *GetSocketRequest) (*GetSocketResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.channelz.v1.Channelz", - Methods: []grpc.MethodDesc{ - { - MethodName: "GetTopChannels", - Handler: srvCopy.getTopChannels, - }, - { - MethodName: "GetServers", - Handler: srvCopy.getServers, - }, - { - MethodName: "GetServer", - Handler: srvCopy.getServer, - }, - { - MethodName: "GetServerSockets", - Handler: srvCopy.getServerSockets, - }, - { - MethodName: "GetChannel", - Handler: srvCopy.getChannel, - }, - { - MethodName: "GetSubchannel", - Handler: srvCopy.getSubchannel, - }, - { - MethodName: "GetSocket", - Handler: srvCopy.getSocket, - }, +var _Channelz_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.channelz.v1.Channelz", + HandlerType: (*ChannelzServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetTopChannels", + Handler: _Channelz_GetTopChannels_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc/channelz/v1/channelz.proto", - } - - s.RegisterService(&sd, nil) -} - -// ChannelzServer is the service API for Channelz service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type ChannelzServer interface { - // Gets all root channels (i.e. channels the application has directly - // created). This does not include subchannels nor non-top level channels. - GetTopChannels(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) - // Gets all servers that exist in the process. - GetServers(context.Context, *GetServersRequest) (*GetServersResponse, error) - // Returns a single Server, or else a NOT_FOUND code. - GetServer(context.Context, *GetServerRequest) (*GetServerResponse, error) - // Gets all server sockets that exist in the process. - GetServerSockets(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) - // Returns a single Channel, or else a NOT_FOUND code. - GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) - // Returns a single Subchannel, or else a NOT_FOUND code. - GetSubchannel(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) - // Returns a single Socket or else a NOT_FOUND code. - GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) -} - -// UnimplementedChannelzServer can be embedded to have forward compatible implementations of -// ChannelzServer -type UnimplementedChannelzServer struct { -} - -func (UnimplementedChannelzServer) GetTopChannels(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetTopChannels not implemented") -} -func (UnimplementedChannelzServer) GetServers(context.Context, *GetServersRequest) (*GetServersResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServers not implemented") -} -func (UnimplementedChannelzServer) GetServer(context.Context, *GetServerRequest) (*GetServerResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServer not implemented") -} -func (UnimplementedChannelzServer) GetServerSockets(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetServerSockets not implemented") -} -func (UnimplementedChannelzServer) GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetChannel not implemented") -} -func (UnimplementedChannelzServer) GetSubchannel(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetSubchannel not implemented") -} -func (UnimplementedChannelzServer) GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented") -} - -// RegisterChannelzServer registers a service implementation with a gRPC server. -func RegisterChannelzServer(s grpc.ServiceRegistrar, srv ChannelzServer) { - str := &ChannelzService{ - GetTopChannels: srv.GetTopChannels, - GetServers: srv.GetServers, - GetServer: srv.GetServer, - GetServerSockets: srv.GetServerSockets, - GetChannel: srv.GetChannel, - GetSubchannel: srv.GetSubchannel, - GetSocket: srv.GetSocket, - } - RegisterChannelzService(s, str) + { + MethodName: "GetServers", + Handler: _Channelz_GetServers_Handler, + }, + { + MethodName: "GetServer", + Handler: _Channelz_GetServer_Handler, + }, + { + MethodName: "GetServerSockets", + Handler: _Channelz_GetServerSockets_Handler, + }, + { + MethodName: "GetChannel", + Handler: _Channelz_GetChannel_Handler, + }, + { + MethodName: "GetSubchannel", + Handler: _Channelz_GetSubchannel_Handler, + }, + { + MethodName: "GetSocket", + Handler: _Channelz_GetSocket_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "grpc/channelz/v1/channelz.proto", } diff --git a/cmd/protoc-gen-go-grpc/README.md b/cmd/protoc-gen-go-grpc/README.md index 152c68a191d..4758125de0d 100644 --- a/cmd/protoc-gen-go-grpc/README.md +++ b/cmd/protoc-gen-go-grpc/README.md @@ -4,115 +4,18 @@ This tool generates Go language bindings of `service`s in protobuf definition files for gRPC. For usage information, please see our [quick start guide](https://grpc.io/docs/languages/go/quickstart/). -## Service implementation and registration +## Future-proofing services -**NOTE:** service registration has changed from the previous version of the -code generator. Please read this section carefully if you are migrating. +By default, to register services using the methods generated by this tool, the +service implementations must embed the corresponding +`UnimplementedServer` for future compatibility. This is a behavior +change from the grpc code generator previously included with `protoc-gen-go`. +To restore this behavior, set the option `require_unimplemented_servers=false`. +E.g.: -To register your service handlers with a gRPC server, first implement the -methods as either functions or methods on a struct. Examples: - -```go -// As a function: - -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { - // Echo.UnaryEcho implementation -} - -// As a struct + method: - -type myEchoService struct { - // ...fields used by this service... -} - -func (s *myEchoService) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { - // Echo.UnaryEcho implementation -} ``` - -Then create an instance of the generated `Service` struct type and initialize -the handlers which have been implemented: - -```go -func main() { - // ... - - // As a function: - echoService := pb.EchoService{ - UnaryEcho: unaryEcho, - // etc - } - - // As a struct+method: - mes := &myEchoService{...} - echoService := pb.EchoService{ - UnaryEcho: mes.UnaryEcho, - // etc - } - - // ... - } -``` - -Finally, pass this `Service` instance to the generated `Register` function: - -```go - pb.RegisterEchoService(grpcServer, echoService) -``` - -### Migration from legacy version - -Older versions of `protoc-gen-go-grpc` and `protoc-gen-go` with the grpc plugin -used a different method to register services. With that method, it was only -possible to register a service implementation that was a complete -implementation of the service. It was also possible to embed an -`Unimplemented` implementation of the service, which was also generated and -returned an UNIMPLEMENTED status for all methods. - -#### Generating the legacy API - -To avoid the need to update existing code, an option has been added to the code -generator to produce the legacy API alongside the new API. To use it: - -```sh -# Example 1: with OPTS set to common options for protoc-gen-go and -# protoc-gen-go-grpc -protoc --go_out=${OPTS}:. --go-grpc_out=${OPTS},gen_unstable_server_interfaces=true:. *.proto - -# Example 2: if no special options are needed -protoc --go_out=:. --go-grpc_out=gen_unstable_server_interfaces=true:. *.proto + protoc --go-grpc_out=require_unimplemented_servers=false[,other options...]:. \ ``` -**The use of this legacy API is NOT recommended.** It was discontinued as it -results in compilation breakages when new methods are added to services, which -is a backward-compatible change in all other languages supported by gRPC. With -the newer API, newly-added methods will return an UNIMPLEMENTED status. - -#### Updating existing code - -To convert your existing code using the previous code generator, please refer -to the following example: - -```go -type myEchoService{ - // ...fields used by this service... -} -// ... method handler implementation ... - - -func main() { - // ... - - // OLD: - pb.RegisterEchoServer(grpcServer, &myEchoService{}) - - // NEW: - es := &myEchoService{} - pb.RegisterEchoService(grpcServer, pb.EchoService{ - UnaryEcho: es.UnaryEcho, - // enumerate all methods in EchoService implemented by myEchoService... - }) - - // ... -} -``` +Note that this is not recommended, and the option is only provided to restore +backward compatibility with previously-generated code. diff --git a/cmd/protoc-gen-go-grpc/grpc.go b/cmd/protoc-gen-go-grpc/grpc.go index 358bae2fe53..919b5d46ae7 100644 --- a/cmd/protoc-gen-go-grpc/grpc.go +++ b/cmd/protoc-gen-go-grpc/grpc.go @@ -61,15 +61,11 @@ func generateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen. g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion7")) g.P() for _, service := range file.Services { - genClient(gen, file, g, service) genService(gen, file, g, service) - if *genUnstableServerInterfaces { - genUnstableServerInterface(gen, file, g, service) - } } } -func genClient(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { +func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { clientName := service.GoName + "Client" g.P("// ", clientName, " is the client API for ", service.GoName, " service.") @@ -109,10 +105,129 @@ func genClient(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedF g.P("}") g.P() + var methodIndex, streamIndex int // Client method implementations. for _, method := range service.Methods { - genClientMethod(gen, g, method) + if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { + // Unary RPC method + genClientMethod(gen, file, g, method, methodIndex) + methodIndex++ + } else { + // Streaming RPC method + genClientMethod(gen, file, g, method, streamIndex) + streamIndex++ + } + } + + mustOrShould := "must" + if !*requireUnimplemented { + mustOrShould = "should" + } + + // Server interface. + serverType := service.GoName + "Server" + g.P("// ", serverType, " is the server API for ", service.GoName, " service.") + g.P("// All implementations ", mustOrShould, " embed Unimplemented", serverType) + g.P("// for forward compatibility") + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P("//") + g.P(deprecationComment) + } + g.Annotate(serverType, service.Location) + g.P("type ", serverType, " interface {") + for _, method := range service.Methods { + g.Annotate(serverType+"."+method.GoName, method.Location) + if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { + g.P(deprecationComment) + } + g.P(method.Comments.Leading, + serverSignature(g, method)) + } + if *requireUnimplemented { + g.P("mustEmbedUnimplemented", serverType, "()") + } + g.P("}") + g.P() + + // Server Unimplemented struct for forward compatibility. + g.P("// Unimplemented", serverType, " ", mustOrShould, " be embedded to have forward compatible implementations.") + g.P("type Unimplemented", serverType, " struct {") + g.P("}") + g.P() + for _, method := range service.Methods { + nilArg := "" + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + nilArg = "nil," + } + g.P("func (Unimplemented", serverType, ") ", serverSignature(g, method), "{") + g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`) + g.P("}") + } + if *requireUnimplemented { + g.P("func (Unimplemented", serverType, ") mustEmbedUnimplemented", serverType, "() {}") + } + g.P() + + // Unsafe Server interface to opt-out of forward compatibility. + g.P("// Unsafe", serverType, " may be embedded to opt out of forward compatibility for this service.") + g.P("// Use of this interface is not recommended, as added methods to ", serverType, " will") + g.P("// result in compilation errors.") + g.P("type Unsafe", serverType, " interface {") + g.P("mustEmbedUnimplemented", serverType, "()") + g.P("}") + + // Server registration. + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P(deprecationComment) + } + serviceDescVar := "_" + service.GoName + "_serviceDesc" + g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {") + g.P("s.RegisterService(&", serviceDescVar, `, srv)`) + g.P("}") + g.P() + + // Server handler implementations. + var handlerNames []string + for _, method := range service.Methods { + hname := genServerMethod(gen, file, g, method) + handlerNames = append(handlerNames, hname) + } + + // Service descriptor. + g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {") + g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",") + g.P("HandlerType: (*", serverType, ")(nil),") + g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{") + for i, method := range service.Methods { + if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { + continue + } + g.P("{") + g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",") + g.P("Handler: ", handlerNames[i], ",") + g.P("},") + } + g.P("},") + g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{") + for i, method := range service.Methods { + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + continue + } + g.P("{") + g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",") + g.P("Handler: ", handlerNames[i], ",") + if method.Desc.IsStreamingServer() { + g.P("ServerStreams: true,") + } + if method.Desc.IsStreamingClient() { + g.P("ClientStreams: true,") + } + g.P("},") } + g.P("},") + g.P("Metadata: \"", file.Desc.Path(), "\",") + g.P("}") + g.P() } func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string { @@ -130,25 +245,13 @@ func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string return s } -func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) { +func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) { service := method.Parent sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name()) if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { g.P(deprecationComment) } - - streamDescName := unexport(service.GoName) + method.GoName + "StreamDesc" - g.P("var ", streamDescName, " = &", grpcPackage.Ident("StreamDesc"), "{") - g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",") - if method.Desc.IsStreamingServer() { - g.P("ServerStreams: true,") - } - if method.Desc.IsStreamingClient() { - g.P("ClientStreams: true,") - } - g.P("}") - g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{") if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { g.P("out := new(", method.Output.GoIdent, ")") @@ -160,8 +263,8 @@ func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *pr return } streamType := unexport(service.GoName) + method.GoName + "Client" - - g.P(`stream, err := c.cc.NewStream(ctx, `, streamDescName, `, "`, sname, `", opts...)`) + serviceDescVar := "_" + service.GoName + "_serviceDesc" + g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.Desc.IsStreamingClient() { @@ -221,175 +324,7 @@ func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *pr } } -func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - // Server struct. - serviceType := service.GoName + "Service" - g.P("// ", serviceType, " is the service API for ", service.GoName, " service.") - g.P("// Fields should be assigned to their respective handler implementations only before") - g.P("// Register", serviceType, " is called. Any unassigned fields will result in the") - g.P("// handler for that method returning an Unimplemented error.") - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.Annotate(serviceType, service.Location) - g.P("type ", serviceType, " struct {") - for _, method := range service.Methods { - if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.Annotate(serviceType+"."+method.GoName, method.Location) - g.P(method.Comments.Leading, - method.GoName, " func", handlerSignature(g, method)) - } - g.P("}") - g.P() - - // Method handler implementations. - for _, method := range service.Methods { - genMethodHandler(gen, g, method) - } - - // Stream interfaces and implementations. - for _, method := range service.Methods { - genServerStreamTypes(gen, g, method) - } - - // Service registration. - genRegisterFunction(gen, file, g, service) -} - -func genRegisterFunction(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - g.P("// Register", service.GoName, "Service registers a service implementation with a gRPC server.") - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.P("func Register", service.GoName, "Service(s ", grpcPackage.Ident("ServiceRegistrar"), ", srv *", service.GoName, "Service) {") - g.P("srvCopy := *srv") - // Add Unimplemented defaults for unset handlers - for _, method := range service.Methods { - g.P("if srvCopy.", method.GoName, " == nil {") - g.P("srvCopy.", method.GoName, " = func", handlerSignature(g, method), "{") - nilArg := "" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - nilArg = "nil, " - } - g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`) - g.P("}") - g.P("}") - } - - // Service descriptor. - g.P("sd := ", grpcPackage.Ident("ServiceDesc"), " {") - g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",") - g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{") - for _, method := range service.Methods { - if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { - continue - } - g.P("{") - g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",") - g.P("Handler: srvCopy.", unexport(method.GoName), ",") - g.P("},") - } - g.P("},") - g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{") - for _, method := range service.Methods { - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - continue - } - g.P("{") - g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",") - g.P("Handler: srvCopy.", unexport(method.GoName), ",") - if method.Desc.IsStreamingServer() { - g.P("ServerStreams: true,") - } - if method.Desc.IsStreamingClient() { - g.P("ClientStreams: true,") - } - g.P("},") - } - g.P("},") - g.P("Metadata: \"", file.Desc.Path(), "\",") - g.P("}") - g.P() - - g.P("s.RegisterService(&sd, nil)") - g.P("}") - g.P() -} - -func genUnstableServerInterface(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - // Service interface. - serverType := service.GoName + "Server" - g.P("// ", serverType, " is the service API for ", service.GoName, " service.") - g.P("// New methods may be added to this interface if they are added to the service") - g.P("// definition, which is not a backward-compatible change. For this reason, ") - g.P("// use of this type is not recommended unless you own the service definition.") - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.Annotate(serverType, service.Location) - g.P("type ", serverType, " interface {") - for _, method := range service.Methods { - g.Annotate(serverType+"."+method.GoName, method.Location) - if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.P(method.Comments.Leading, - methodSignature(g, method)) - } - g.P("}") - g.P() - - // Unimplemented implementation. - genUnimplementedServer(gen, file, g, service) - - // Service registration. - genUnstableRegisterFunction(gen, file, g, service) -} - -func genUnimplementedServer(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - // Server Unimplemented struct for forward compatibility. - serverType := service.GoName + "Server" - g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations of") - g.P("// ", serverType) - g.P("type Unimplemented", serverType, " struct {") - g.P("}") - g.P() - for _, method := range service.Methods { - nilArg := "" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - nilArg = "nil," - } - g.P("func (Unimplemented", serverType, ") ", methodSignature(g, method), "{") - g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`) - g.P("}") - } - g.P() -} - -func genUnstableRegisterFunction(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - serverType := service.GoName + "Server" - g.P("// Register", serverType, " registers a service implementation with a gRPC server.") - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.P("func Register", serverType, "(s ", grpcPackage.Ident("ServiceRegistrar"), ", srv ", serverType, ") {") - g.P("str := &", service.GoName, "Service{") - for _, method := range service.Methods { - g.P(method.GoName, ": srv.", method.GoName, ",") - } - g.P("}") - g.P("Register", service.GoName, "Service(s, str)") - g.P("}") - g.P() -} - -func methodSignature(g *protogen.GeneratedFile, method *protogen.Method) string { +func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string { var reqArgs []string ret := "error" if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { @@ -405,80 +340,39 @@ func methodSignature(g *protogen.GeneratedFile, method *protogen.Method) string return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret } -func handlerSignature(g *protogen.GeneratedFile, method *protogen.Method) string { - var reqArgs []string - ret := "error" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context"))) - ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)" - } - if !method.Desc.IsStreamingClient() { - reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent)) - } - if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { - reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server") - } - return "(" + strings.Join(reqArgs, ", ") + ") " + ret -} - -func genericHandlerSignature(g *protogen.GeneratedFile, method *protogen.Method) string { - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - // Unary - return "(_ interface{}, ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context")) + - ", dec func(interface{}) error, interceptor " + - g.QualifiedGoIdent(grpcPackage.Ident("UnaryServerInterceptor")) + ") (interface{}, error)" - } - // Streaming - return "(_ interface{}, stream " + g.QualifiedGoIdent(grpcPackage.Ident("ServerStream")) + ") error" -} - -func genMethodHandler(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) { +func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string { service := method.Parent + hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName) - g.P("func (s *", service.GoName, "Service) ", unexport(method.GoName), genericHandlerSignature(g, method), " {") - - // Unary if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {") g.P("in := new(", method.Input.GoIdent, ")") g.P("if err := dec(in); err != nil { return nil, err }") - - g.P("if interceptor == nil {") - g.P("return s.", method.GoName, "(ctx, in)") - g.P("}") - + g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }") g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{") - g.P("Server: s,") + g.P("Server: srv,") g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",") g.P("}") g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {") - g.P("return s.", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))") + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))") g.P("}") g.P("return interceptor(ctx, in, info, handler)") g.P("}") - return + g.P() + return hname } - - // Streaming streamType := unexport(service.GoName) + method.GoName + "Server" + g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {") if !method.Desc.IsStreamingClient() { - // Server-streaming g.P("m := new(", method.Input.GoIdent, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") - g.P("return s.", method.GoName, "(m, &", streamType, "{stream})") + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})") } else { - // Bidi-streaming - g.P("return s.", method.GoName, "(&", streamType, "{stream})") + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})") } g.P("}") -} + g.P() -func genServerStreamTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) { - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - // Unary method - return - } - service := method.Parent - streamType := unexport(service.GoName) + method.GoName + "Server" genSend := method.Desc.IsStreamingServer() genSendAndClose := !method.Desc.IsStreamingServer() genRecv := method.Desc.IsStreamingClient() @@ -524,7 +418,7 @@ func genServerStreamTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, metho g.P() } - return + return hname } const deprecationComment = "// Deprecated: Do not use." diff --git a/cmd/protoc-gen-go-grpc/main.go b/cmd/protoc-gen-go-grpc/main.go index 65896f13188..dcb2e0efe92 100644 --- a/cmd/protoc-gen-go-grpc/main.go +++ b/cmd/protoc-gen-go-grpc/main.go @@ -34,19 +34,17 @@ import ( "flag" "google.golang.org/protobuf/compiler/protogen" - "google.golang.org/protobuf/types/pluginpb" ) -var genUnstableServerInterfaces *bool +var requireUnimplemented *bool func main() { var flags flag.FlagSet - genUnstableServerInterfaces = flags.Bool("gen_unstable_server_interfaces", false, `set to generate legacy "Server" interfaces which do not guarantee backward compatibility`) + requireUnimplemented = flags.Bool("require_unimplemented_servers", true, "set to false to match legacy behavior") protogen.Options{ ParamFunc: flags.Set, }.Run(func(gen *protogen.Plugin) error { - gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL) for _, f := range gen.Files { if !f.Generate { continue diff --git a/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go b/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go index 2b06da50df2..d27bd063ee2 100644 --- a/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go +++ b/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go @@ -34,14 +34,8 @@ func NewHandshakerServiceClient(cc grpc.ClientConnInterface) HandshakerServiceCl return &handshakerServiceClient{cc} } -var handshakerServiceDoHandshakeStreamDesc = &grpc.StreamDesc{ - StreamName: "DoHandshake", - ServerStreams: true, - ClientStreams: true, -} - func (c *handshakerServiceClient) DoHandshake(ctx context.Context, opts ...grpc.CallOption) (HandshakerService_DoHandshakeClient, error) { - stream, err := c.cc.NewStream(ctx, handshakerServiceDoHandshakeStreamDesc, "/grpc.gcp.HandshakerService/DoHandshake", opts...) + stream, err := c.cc.NewStream(ctx, &_HandshakerService_serviceDesc.Streams[0], "/grpc.gcp.HandshakerService/DoHandshake", opts...) if err != nil { return nil, err } @@ -71,22 +65,42 @@ func (x *handshakerServiceDoHandshakeClient) Recv() (*HandshakerResp, error) { return m, nil } -// HandshakerServiceService is the service API for HandshakerService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterHandshakerServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type HandshakerServiceService struct { +// HandshakerServiceServer is the server API for HandshakerService service. +// All implementations must embed UnimplementedHandshakerServiceServer +// for forward compatibility +type HandshakerServiceServer interface { // Handshaker service accepts a stream of handshaker request, returning a // stream of handshaker response. Client is expected to send exactly one // message with either client_start or server_start followed by one or more // messages with next. Each time client sends a request, the handshaker // service expects to respond. Client does not have to wait for service's // response before sending next request. - DoHandshake func(HandshakerService_DoHandshakeServer) error + DoHandshake(HandshakerService_DoHandshakeServer) error + mustEmbedUnimplementedHandshakerServiceServer() +} + +// UnimplementedHandshakerServiceServer must be embedded to have forward compatible implementations. +type UnimplementedHandshakerServiceServer struct { } -func (s *HandshakerServiceService) doHandshake(_ interface{}, stream grpc.ServerStream) error { - return s.DoHandshake(&handshakerServiceDoHandshakeServer{stream}) +func (UnimplementedHandshakerServiceServer) DoHandshake(HandshakerService_DoHandshakeServer) error { + return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented") +} +func (UnimplementedHandshakerServiceServer) mustEmbedUnimplementedHandshakerServiceServer() {} + +// UnsafeHandshakerServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to HandshakerServiceServer will +// result in compilation errors. +type UnsafeHandshakerServiceServer interface { + mustEmbedUnimplementedHandshakerServiceServer() +} + +func RegisterHandshakerServiceServer(s *grpc.Server, srv HandshakerServiceServer) { + s.RegisterService(&_HandshakerService_serviceDesc, srv) +} + +func _HandshakerService_DoHandshake_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(HandshakerServiceServer).DoHandshake(&handshakerServiceDoHandshakeServer{stream}) } type HandshakerService_DoHandshakeServer interface { @@ -111,58 +125,17 @@ func (x *handshakerServiceDoHandshakeServer) Recv() (*HandshakerReq, error) { return m, nil } -// RegisterHandshakerServiceService registers a service implementation with a gRPC server. -func RegisterHandshakerServiceService(s grpc.ServiceRegistrar, srv *HandshakerServiceService) { - srvCopy := *srv - if srvCopy.DoHandshake == nil { - srvCopy.DoHandshake = func(HandshakerService_DoHandshakeServer) error { - return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.gcp.HandshakerService", - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "DoHandshake", - Handler: srvCopy.doHandshake, - ServerStreams: true, - ClientStreams: true, - }, +var _HandshakerService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.gcp.HandshakerService", + HandlerType: (*HandshakerServiceServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "DoHandshake", + Handler: _HandshakerService_DoHandshake_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "grpc/gcp/handshaker.proto", - } - - s.RegisterService(&sd, nil) -} - -// HandshakerServiceServer is the service API for HandshakerService service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type HandshakerServiceServer interface { - // Handshaker service accepts a stream of handshaker request, returning a - // stream of handshaker response. Client is expected to send exactly one - // message with either client_start or server_start followed by one or more - // messages with next. Each time client sends a request, the handshaker - // service expects to respond. Client does not have to wait for service's - // response before sending next request. - DoHandshake(HandshakerService_DoHandshakeServer) error -} - -// UnimplementedHandshakerServiceServer can be embedded to have forward compatible implementations of -// HandshakerServiceServer -type UnimplementedHandshakerServiceServer struct { -} - -func (UnimplementedHandshakerServiceServer) DoHandshake(HandshakerService_DoHandshakeServer) error { - return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented") -} - -// RegisterHandshakerServiceServer registers a service implementation with a gRPC server. -func RegisterHandshakerServiceServer(s grpc.ServiceRegistrar, srv HandshakerServiceServer) { - str := &HandshakerServiceService{ - DoHandshake: srv.DoHandshake, - } - RegisterHandshakerServiceService(s, str) + }, + Metadata: "grpc/gcp/handshaker.proto", } diff --git a/credentials/tls/certprovider/meshca/internal/v1/meshca_grpc.pb.go b/credentials/tls/certprovider/meshca/internal/v1/meshca_grpc.pb.go index 35b3681491d..ab591929278 100644 --- a/credentials/tls/certprovider/meshca/internal/v1/meshca_grpc.pb.go +++ b/credentials/tls/certprovider/meshca/internal/v1/meshca_grpc.pb.go @@ -30,10 +30,6 @@ func NewMeshCertificateServiceClient(cc grpc.ClientConnInterface) MeshCertificat return &meshCertificateServiceClient{cc} } -var meshCertificateServiceCreateCertificateStreamDesc = &grpc.StreamDesc{ - StreamName: "CreateCertificate", -} - func (c *meshCertificateServiceClient) CreateCertificate(ctx context.Context, in *MeshCertificateRequest, opts ...grpc.CallOption) (*MeshCertificateResponse, error) { out := new(MeshCertificateResponse) err := c.cc.Invoke(ctx, "/google.security.meshca.v1.MeshCertificateService/CreateCertificate", in, out, opts...) @@ -43,80 +39,64 @@ func (c *meshCertificateServiceClient) CreateCertificate(ctx context.Context, in return out, nil } -// MeshCertificateServiceService is the service API for MeshCertificateService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterMeshCertificateServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type MeshCertificateServiceService struct { +// MeshCertificateServiceServer is the server API for MeshCertificateService service. +// All implementations must embed UnimplementedMeshCertificateServiceServer +// for forward compatibility +type MeshCertificateServiceServer interface { // Using provided CSR, returns a signed certificate that represents a GCP // service account identity. - CreateCertificate func(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) + CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) + mustEmbedUnimplementedMeshCertificateServiceServer() +} + +// UnimplementedMeshCertificateServiceServer must be embedded to have forward compatible implementations. +type UnimplementedMeshCertificateServiceServer struct { +} + +func (UnimplementedMeshCertificateServiceServer) CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented") +} +func (UnimplementedMeshCertificateServiceServer) mustEmbedUnimplementedMeshCertificateServiceServer() { +} + +// UnsafeMeshCertificateServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to MeshCertificateServiceServer will +// result in compilation errors. +type UnsafeMeshCertificateServiceServer interface { + mustEmbedUnimplementedMeshCertificateServiceServer() } -func (s *MeshCertificateServiceService) createCertificate(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterMeshCertificateServiceServer(s *grpc.Server, srv MeshCertificateServiceServer) { + s.RegisterService(&_MeshCertificateService_serviceDesc, srv) +} + +func _MeshCertificateService_CreateCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MeshCertificateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.CreateCertificate(ctx, in) + return srv.(MeshCertificateServiceServer).CreateCertificate(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/google.security.meshca.v1.MeshCertificateService/CreateCertificate", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.CreateCertificate(ctx, req.(*MeshCertificateRequest)) + return srv.(MeshCertificateServiceServer).CreateCertificate(ctx, req.(*MeshCertificateRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterMeshCertificateServiceService registers a service implementation with a gRPC server. -func RegisterMeshCertificateServiceService(s grpc.ServiceRegistrar, srv *MeshCertificateServiceService) { - srvCopy := *srv - if srvCopy.CreateCertificate == nil { - srvCopy.CreateCertificate = func(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "google.security.meshca.v1.MeshCertificateService", - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateCertificate", - Handler: srvCopy.createCertificate, - }, +var _MeshCertificateService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "google.security.meshca.v1.MeshCertificateService", + HandlerType: (*MeshCertificateServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CreateCertificate", + Handler: _MeshCertificateService_CreateCertificate_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "istio/google/security/meshca/v1/meshca.proto", - } - - s.RegisterService(&sd, nil) -} - -// MeshCertificateServiceServer is the service API for MeshCertificateService service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type MeshCertificateServiceServer interface { - // Using provided CSR, returns a signed certificate that represents a GCP - // service account identity. - CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) -} - -// UnimplementedMeshCertificateServiceServer can be embedded to have forward compatible implementations of -// MeshCertificateServiceServer -type UnimplementedMeshCertificateServiceServer struct { -} - -func (UnimplementedMeshCertificateServiceServer) CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented") -} - -// RegisterMeshCertificateServiceServer registers a service implementation with a gRPC server. -func RegisterMeshCertificateServiceServer(s grpc.ServiceRegistrar, srv MeshCertificateServiceServer) { - str := &MeshCertificateServiceService{ - CreateCertificate: srv.CreateCertificate, - } - RegisterMeshCertificateServiceService(s, str) + }, + Streams: []grpc.StreamDesc{}, + Metadata: "istio/google/security/meshca/v1/meshca.proto", } diff --git a/examples/features/authentication/server/main.go b/examples/features/authentication/server/main.go index 505e8cb0984..5163fc31671 100644 --- a/examples/features/authentication/server/main.go +++ b/examples/features/authentication/server/main.go @@ -63,7 +63,7 @@ func main() { grpc.Creds(credentials.NewServerTLSFromCert(&cert)), } s := grpc.NewServer(opts...) - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &ecServer{}) lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) if err != nil { log.Fatalf("failed to listen: %v", err) @@ -73,7 +73,11 @@ func main() { } } -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +type ecServer struct { + pb.UnimplementedEchoServer +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{Message: req.Message}, nil } diff --git a/examples/features/cancellation/server/main.go b/examples/features/cancellation/server/main.go index 1896828f2c9..520286bf193 100644 --- a/examples/features/cancellation/server/main.go +++ b/examples/features/cancellation/server/main.go @@ -33,7 +33,11 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { for { in, err := stream.Recv() if err != nil { @@ -57,6 +61,6 @@ func main() { } fmt.Printf("server listening at port %v\n", lis.Addr()) s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{BidirectionalStreamingEcho: bidirectionalStreamingEcho}) + pb.RegisterEchoServer(s, &server{}) s.Serve(lis) } diff --git a/examples/features/compression/server/main.go b/examples/features/compression/server/main.go index 442d196085c..e495cc89106 100644 --- a/examples/features/compression/server/main.go +++ b/examples/features/compression/server/main.go @@ -34,7 +34,11 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage()) return &pb.EchoResponse{Message: in.Message}, nil } @@ -49,6 +53,6 @@ func main() { fmt.Printf("server listening at %v\n", lis.Addr()) s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &server{}) s.Serve(lis) } diff --git a/examples/features/deadline/server/main.go b/examples/features/deadline/server/main.go index f5a033db3d9..11cd47a6b5b 100644 --- a/examples/features/deadline/server/main.go +++ b/examples/features/deadline/server/main.go @@ -40,6 +40,7 @@ var port = flag.Int("port", 50052, "port number") // server is used to implement EchoServer. type server struct { + pb.UnimplementedEchoServer client pb.EchoClient cc *grpc.ClientConn } @@ -111,12 +112,9 @@ func main() { echoServer := newEchoServer() defer echoServer.Close() - grpcServer := grpc.NewServer() - pb.RegisterEchoService(grpcServer, &pb.EchoService{ - UnaryEcho: echoServer.UnaryEcho, - BidirectionalStreamingEcho: echoServer.BidirectionalStreamingEcho, - }) + grpcServer := grpc.NewServer() + pb.RegisterEchoServer(grpcServer, echoServer) if err := grpcServer.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/debugging/server/main.go b/examples/features/debugging/server/main.go index 839212c99fb..397cb0c781e 100644 --- a/examples/features/debugging/server/main.go +++ b/examples/features/debugging/server/main.go @@ -36,13 +36,23 @@ var ( ports = []string{":10001", ":10002", ":10003"} ) -// sayHello implements helloworld.GreeterServer.SayHello -func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { +// server is used to implement helloworld.GreeterServer. +type server struct { + pb.UnimplementedGreeterServer +} + +// SayHello implements helloworld.GreeterServer +func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil } -// sayHelloSlow implements helloworld.GreeterServer.SayHello -func sayHelloSlow(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { +// slow server is used to simulate a server that has a variable delay in its response. +type slowServer struct { + pb.UnimplementedGreeterServer +} + +// SayHello implements helloworld.GreeterServer +func (s *slowServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { // Delay 100ms ~ 200ms before replying time.Sleep(time.Duration(100+grpcrand.Intn(100)) * time.Millisecond) return &pb.HelloReply{Message: "Hello " + in.Name}, nil @@ -60,7 +70,7 @@ func main() { go s.Serve(lis) defer s.Stop() - /***** Start three GreeterServers(with one of them to be the slow server). *****/ + /***** Start three GreeterServers(with one of them to be the slowServer). *****/ for i := 0; i < 3; i++ { lis, err := net.Listen("tcp", ports[i]) if err != nil { @@ -69,9 +79,9 @@ func main() { defer lis.Close() s := grpc.NewServer() if i == 2 { - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHelloSlow}) + pb.RegisterGreeterServer(s, &slowServer{}) } else { - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) + pb.RegisterGreeterServer(s, &server{}) } go s.Serve(lis) } diff --git a/examples/features/encryption/ALTS/server/main.go b/examples/features/encryption/ALTS/server/main.go index a72ccd11e7f..87bedd810f4 100644 --- a/examples/features/encryption/ALTS/server/main.go +++ b/examples/features/encryption/ALTS/server/main.go @@ -34,7 +34,11 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +type ecServer struct { + pb.UnimplementedEchoServer +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{Message: req.Message}, nil } @@ -50,8 +54,8 @@ func main() { s := grpc.NewServer(grpc.Creds(altsTC)) - // Register EchoService on the server. - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + // Register EchoServer on the server. + pb.RegisterEchoServer(s, &ecServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/encryption/TLS/server/main.go b/examples/features/encryption/TLS/server/main.go index d5ea6ccfcaf..81bf1f3acc3 100644 --- a/examples/features/encryption/TLS/server/main.go +++ b/examples/features/encryption/TLS/server/main.go @@ -35,7 +35,11 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +type ecServer struct { + pb.UnimplementedEchoServer +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{Message: req.Message}, nil } @@ -56,7 +60,7 @@ func main() { s := grpc.NewServer(grpc.Creds(creds)) // Register EchoServer on the server. - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &ecServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/errors/server/main.go b/examples/features/errors/server/main.go index c6c06a2bf2c..dc337741ad0 100644 --- a/examples/features/errors/server/main.go +++ b/examples/features/errors/server/main.go @@ -39,6 +39,7 @@ var port = flag.Int("port", 50052, "port number") // server is used to implement helloworld.GreeterServer. type server struct { + pb.UnimplementedGreeterServer mu sync.Mutex count map[string]int } @@ -77,8 +78,7 @@ func main() { } s := grpc.NewServer() - hw := &server{count: make(map[string]int)} - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: hw.SayHello}) + pb.RegisterGreeterServer(s, &server{count: make(map[string]int)}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } diff --git a/examples/features/health/server/main.go b/examples/features/health/server/main.go index 670518da9d0..3f79c8ba347 100644 --- a/examples/features/health/server/main.go +++ b/examples/features/health/server/main.go @@ -40,12 +40,18 @@ var ( system = "" // empty string represents the health of the system ) -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +type echoServer struct { + pb.UnimplementedEchoServer +} + +func (e *echoServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{ Message: fmt.Sprintf("hello from localhost:%d", *port), }, nil } +var _ pb.EchoServer = &echoServer{} + func main() { flag.Parse() @@ -57,7 +63,7 @@ func main() { s := grpc.NewServer() healthcheck := health.NewServer() healthpb.RegisterHealthServer(s, healthcheck) - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &echoServer{}) go func() { // asynchronously inspect dependencies and toggle serving status as needed diff --git a/examples/features/interceptor/server/main.go b/examples/features/interceptor/server/main.go index 5ca5a843251..1b07cdecd6c 100644 --- a/examples/features/interceptor/server/main.go +++ b/examples/features/interceptor/server/main.go @@ -51,12 +51,16 @@ func logger(format string, a ...interface{}) { fmt.Printf("LOG:\t"+format+"\n", a...) } -func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { fmt.Printf("unary echoing message %q\n", in.Message) return &pb.EchoResponse{Message: in.Message}, nil } -func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { +func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { for { in, err := stream.Recv() if err != nil { @@ -152,11 +156,8 @@ func main() { s := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(unaryInterceptor), grpc.StreamInterceptor(streamInterceptor)) - // Register EchoService on the server. - pb.RegisterEchoService(s, &pb.EchoService{ - UnaryEcho: unaryEcho, - BidirectionalStreamingEcho: bidirectionalStreamingEcho, - }) + // Register EchoServer on the server. + pb.RegisterEchoServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/keepalive/server/main.go b/examples/features/keepalive/server/main.go index e3ec8ae0679..beaa8f71088 100644 --- a/examples/features/keepalive/server/main.go +++ b/examples/features/keepalive/server/main.go @@ -48,7 +48,12 @@ var kasp = keepalive.ServerParameters{ Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead } -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +// server implements EchoServer. +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{Message: req.Message}, nil } @@ -62,7 +67,7 @@ func main() { } s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp)) - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/load_balancing/server/main.go b/examples/features/load_balancing/server/main.go index 680895fe50f..9d179579ed4 100644 --- a/examples/features/load_balancing/server/main.go +++ b/examples/features/load_balancing/server/main.go @@ -36,6 +36,7 @@ var ( ) type ecServer struct { + pb.UnimplementedEchoServer addr string } @@ -49,8 +50,7 @@ func startServer(addr string) { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - e := &ecServer{addr: addr} - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: e.UnaryEcho}) + pb.RegisterEchoServer(s, &ecServer{addr: addr}) log.Printf("serving on %s\n", addr) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/metadata/server/main.go b/examples/features/metadata/server/main.go index af12a3a65d1..cda3b497869 100644 --- a/examples/features/metadata/server/main.go +++ b/examples/features/metadata/server/main.go @@ -44,7 +44,11 @@ const ( streamingCount = 10 ) -func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { fmt.Printf("--- UnaryEcho ---\n") // Create trailer in defer to record function return time. defer func() { @@ -73,7 +77,7 @@ func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error return &pb.EchoResponse{Message: in.Message}, nil } -func serverStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error { +func (s *server) ServerStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error { fmt.Printf("--- ServerStreamingEcho ---\n") // Create trailer in defer to record function return time. defer func() { @@ -110,7 +114,7 @@ func serverStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoS return nil } -func clientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error { +func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error { fmt.Printf("--- ClientStreamingEcho ---\n") // Create trailer in defer to record function return time. defer func() { @@ -150,7 +154,7 @@ func clientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error { } } -func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { +func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { fmt.Printf("--- BidirectionalStreamingEcho ---\n") // Create trailer in defer to record function return time. defer func() { @@ -201,11 +205,6 @@ func main() { fmt.Printf("server listening at %v\n", lis.Addr()) s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{ - UnaryEcho: unaryEcho, - ServerStreamingEcho: serverStreamingEcho, - ClientStreamingEcho: clientStreamingEcho, - BidirectionalStreamingEcho: bidirectionalStreamingEcho, - }) + pb.RegisterEchoServer(s, &server{}) s.Serve(lis) } diff --git a/examples/features/multiplex/server/main.go b/examples/features/multiplex/server/main.go index d8b13305da2..18da09adda3 100644 --- a/examples/features/multiplex/server/main.go +++ b/examples/features/multiplex/server/main.go @@ -34,13 +34,21 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -// sayHello implements helloworld.GreeterServer.SayHello -func sayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { +// hwServer is used to implement helloworld.GreeterServer. +type hwServer struct { + hwpb.UnimplementedGreeterServer +} + +// SayHello implements helloworld.GreeterServer +func (s *hwServer) SayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil } -// unaryEcho implements echo.Echo.UnaryEcho -func unaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { +type ecServer struct { + ecpb.UnimplementedEchoServer +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { return &ecpb.EchoResponse{Message: req.Message}, nil } @@ -55,10 +63,10 @@ func main() { s := grpc.NewServer() // Register Greeter on the server. - hwpb.RegisterGreeterService(s, &hwpb.GreeterService{SayHello: sayHello}) + hwpb.RegisterGreeterServer(s, &hwServer{}) - // Register Echo on the same server. - ecpb.RegisterEchoService(s, &ecpb.EchoService{UnaryEcho: unaryEcho}) + // Register RouteGuide on the same server. + ecpb.RegisterEchoServer(s, &ecServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/name_resolving/server/main.go b/examples/features/name_resolving/server/main.go index 77d35eb2ada..1977f44d0c5 100644 --- a/examples/features/name_resolving/server/main.go +++ b/examples/features/name_resolving/server/main.go @@ -32,8 +32,13 @@ import ( const addr = "localhost:50051" -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { - return &pb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, addr)}, nil +type ecServer struct { + pb.UnimplementedEchoServer + addr string +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { + return &pb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, s.addr)}, nil } func main() { @@ -42,7 +47,7 @@ func main() { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &ecServer{addr: addr}) log.Printf("serving on %s\n", addr) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/profiling/README.md b/examples/features/profiling/README.md index 8c30a3dbcac..1fd80e9ada2 100644 --- a/examples/features/profiling/README.md +++ b/examples/features/profiling/README.md @@ -41,7 +41,7 @@ type server struct{} func main() error { s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{...}) + pb.RegisterEchoServer(s, &server{}) // Include this to register a profiling-specific service within your server. if err := profsvc.Init(&profsvc.ProfilingConfig{Server: s}); err != nil { diff --git a/examples/features/profiling/server/main.go b/examples/features/profiling/server/main.go index aa0bf11b240..ee0a4f55ab2 100644 --- a/examples/features/profiling/server/main.go +++ b/examples/features/profiling/server/main.go @@ -33,7 +33,11 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage()) return &pb.EchoResponse{Message: in.Message}, nil } @@ -48,7 +52,7 @@ func main() { fmt.Printf("server listening at %v\n", lis.Addr()) s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &server{}) // Register your grpc.Server with profiling. pc := &profsvc.ProfilingConfig{ diff --git a/examples/features/proto/echo/echo_grpc.pb.go b/examples/features/proto/echo/echo_grpc.pb.go index ff30c6524b4..2da0bfeb371 100644 --- a/examples/features/proto/echo/echo_grpc.pb.go +++ b/examples/features/proto/echo/echo_grpc.pb.go @@ -35,10 +35,6 @@ func NewEchoClient(cc grpc.ClientConnInterface) EchoClient { return &echoClient{cc} } -var echoUnaryEchoStreamDesc = &grpc.StreamDesc{ - StreamName: "UnaryEcho", -} - func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error) { out := new(EchoResponse) err := c.cc.Invoke(ctx, "/grpc.examples.echo.Echo/UnaryEcho", in, out, opts...) @@ -48,13 +44,8 @@ func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grp return out, nil } -var echoServerStreamingEchoStreamDesc = &grpc.StreamDesc{ - StreamName: "ServerStreamingEcho", - ServerStreams: true, -} - func (c *echoClient) ServerStreamingEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (Echo_ServerStreamingEchoClient, error) { - stream, err := c.cc.NewStream(ctx, echoServerStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/ServerStreamingEcho", opts...) + stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[0], "/grpc.examples.echo.Echo/ServerStreamingEcho", opts...) if err != nil { return nil, err } @@ -85,13 +76,8 @@ func (x *echoServerStreamingEchoClient) Recv() (*EchoResponse, error) { return m, nil } -var echoClientStreamingEchoStreamDesc = &grpc.StreamDesc{ - StreamName: "ClientStreamingEcho", - ClientStreams: true, -} - func (c *echoClient) ClientStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_ClientStreamingEchoClient, error) { - stream, err := c.cc.NewStream(ctx, echoClientStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/ClientStreamingEcho", opts...) + stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[1], "/grpc.examples.echo.Echo/ClientStreamingEcho", opts...) if err != nil { return nil, err } @@ -124,14 +110,8 @@ func (x *echoClientStreamingEchoClient) CloseAndRecv() (*EchoResponse, error) { return m, nil } -var echoBidirectionalStreamingEchoStreamDesc = &grpc.StreamDesc{ - StreamName: "BidirectionalStreamingEcho", - ServerStreams: true, - ClientStreams: true, -} - func (c *echoClient) BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_BidirectionalStreamingEchoClient, error) { - stream, err := c.cc.NewStream(ctx, echoBidirectionalStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", opts...) + stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[2], "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", opts...) if err != nil { return nil, err } @@ -161,50 +141,74 @@ func (x *echoBidirectionalStreamingEchoClient) Recv() (*EchoResponse, error) { return m, nil } -// EchoService is the service API for Echo service. -// Fields should be assigned to their respective handler implementations only before -// RegisterEchoService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type EchoService struct { +// EchoServer is the server API for Echo service. +// All implementations must embed UnimplementedEchoServer +// for forward compatibility +type EchoServer interface { // UnaryEcho is unary echo. - UnaryEcho func(context.Context, *EchoRequest) (*EchoResponse, error) + UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error) // ServerStreamingEcho is server side streaming. - ServerStreamingEcho func(*EchoRequest, Echo_ServerStreamingEchoServer) error + ServerStreamingEcho(*EchoRequest, Echo_ServerStreamingEchoServer) error // ClientStreamingEcho is client side streaming. - ClientStreamingEcho func(Echo_ClientStreamingEchoServer) error + ClientStreamingEcho(Echo_ClientStreamingEchoServer) error // BidirectionalStreamingEcho is bidi streaming. - BidirectionalStreamingEcho func(Echo_BidirectionalStreamingEchoServer) error + BidirectionalStreamingEcho(Echo_BidirectionalStreamingEchoServer) error + mustEmbedUnimplementedEchoServer() +} + +// UnimplementedEchoServer must be embedded to have forward compatible implementations. +type UnimplementedEchoServer struct { +} + +func (UnimplementedEchoServer) UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented") +} +func (UnimplementedEchoServer) ServerStreamingEcho(*EchoRequest, Echo_ServerStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented") +} +func (UnimplementedEchoServer) ClientStreamingEcho(Echo_ClientStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented") +} +func (UnimplementedEchoServer) BidirectionalStreamingEcho(Echo_BidirectionalStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented") +} +func (UnimplementedEchoServer) mustEmbedUnimplementedEchoServer() {} + +// UnsafeEchoServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to EchoServer will +// result in compilation errors. +type UnsafeEchoServer interface { + mustEmbedUnimplementedEchoServer() } -func (s *EchoService) unaryEcho(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterEchoServer(s *grpc.Server, srv EchoServer) { + s.RegisterService(&_Echo_serviceDesc, srv) +} + +func _Echo_UnaryEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EchoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnaryEcho(ctx, in) + return srv.(EchoServer).UnaryEcho(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.examples.echo.Echo/UnaryEcho", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnaryEcho(ctx, req.(*EchoRequest)) + return srv.(EchoServer).UnaryEcho(ctx, req.(*EchoRequest)) } return interceptor(ctx, in, info, handler) } -func (s *EchoService) serverStreamingEcho(_ interface{}, stream grpc.ServerStream) error { + +func _Echo_ServerStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(EchoRequest) if err := stream.RecvMsg(m); err != nil { return err } - return s.ServerStreamingEcho(m, &echoServerStreamingEchoServer{stream}) -} -func (s *EchoService) clientStreamingEcho(_ interface{}, stream grpc.ServerStream) error { - return s.ClientStreamingEcho(&echoClientStreamingEchoServer{stream}) -} -func (s *EchoService) bidirectionalStreamingEcho(_ interface{}, stream grpc.ServerStream) error { - return s.BidirectionalStreamingEcho(&echoBidirectionalStreamingEchoServer{stream}) + return srv.(EchoServer).ServerStreamingEcho(m, &echoServerStreamingEchoServer{stream}) } type Echo_ServerStreamingEchoServer interface { @@ -220,6 +224,10 @@ func (x *echoServerStreamingEchoServer) Send(m *EchoResponse) error { return x.ServerStream.SendMsg(m) } +func _Echo_ClientStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(EchoServer).ClientStreamingEcho(&echoClientStreamingEchoServer{stream}) +} + type Echo_ClientStreamingEchoServer interface { SendAndClose(*EchoResponse) error Recv() (*EchoRequest, error) @@ -242,6 +250,10 @@ func (x *echoClientStreamingEchoServer) Recv() (*EchoRequest, error) { return m, nil } +func _Echo_BidirectionalStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(EchoServer).BidirectionalStreamingEcho(&echoBidirectionalStreamingEchoServer{stream}) +} + type Echo_BidirectionalStreamingEchoServer interface { Send(*EchoResponse) error Recv() (*EchoRequest, error) @@ -264,57 +276,32 @@ func (x *echoBidirectionalStreamingEchoServer) Recv() (*EchoRequest, error) { return m, nil } -// RegisterEchoService registers a service implementation with a gRPC server. -func RegisterEchoService(s grpc.ServiceRegistrar, srv *EchoService) { - srvCopy := *srv - if srvCopy.UnaryEcho == nil { - srvCopy.UnaryEcho = func(context.Context, *EchoRequest) (*EchoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented") - } - } - if srvCopy.ServerStreamingEcho == nil { - srvCopy.ServerStreamingEcho = func(*EchoRequest, Echo_ServerStreamingEchoServer) error { - return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented") - } - } - if srvCopy.ClientStreamingEcho == nil { - srvCopy.ClientStreamingEcho = func(Echo_ClientStreamingEchoServer) error { - return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented") - } - } - if srvCopy.BidirectionalStreamingEcho == nil { - srvCopy.BidirectionalStreamingEcho = func(Echo_BidirectionalStreamingEchoServer) error { - return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.examples.echo.Echo", - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryEcho", - Handler: srvCopy.unaryEcho, - }, +var _Echo_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.examples.echo.Echo", + HandlerType: (*EchoServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UnaryEcho", + Handler: _Echo_UnaryEcho_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerStreamingEcho", - Handler: srvCopy.serverStreamingEcho, - ServerStreams: true, - }, - { - StreamName: "ClientStreamingEcho", - Handler: srvCopy.clientStreamingEcho, - ClientStreams: true, - }, - { - StreamName: "BidirectionalStreamingEcho", - Handler: srvCopy.bidirectionalStreamingEcho, - ServerStreams: true, - ClientStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "ServerStreamingEcho", + Handler: _Echo_ServerStreamingEcho_Handler, + ServerStreams: true, }, - Metadata: "examples/features/proto/echo/echo.proto", - } - - s.RegisterService(&sd, nil) + { + StreamName: "ClientStreamingEcho", + Handler: _Echo_ClientStreamingEcho_Handler, + ClientStreams: true, + }, + { + StreamName: "BidirectionalStreamingEcho", + Handler: _Echo_BidirectionalStreamingEcho_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "examples/features/proto/echo/echo.proto", } diff --git a/examples/features/reflection/server/main.go b/examples/features/reflection/server/main.go index 1501c01f33a..569273dfdd3 100644 --- a/examples/features/reflection/server/main.go +++ b/examples/features/reflection/server/main.go @@ -35,13 +35,21 @@ import ( var port = flag.Int("port", 50051, "the port to serve on") -// sayHello implements helloworld.GreeterServer.SayHello -func sayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { +// hwServer is used to implement helloworld.GreeterServer. +type hwServer struct { + hwpb.UnimplementedGreeterServer +} + +// SayHello implements helloworld.GreeterServer +func (s *hwServer) SayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil } -// unaryEcho implements echo.Echo.UnaryEcho -func unaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { +type ecServer struct { + ecpb.UnimplementedEchoServer +} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { return &ecpb.EchoResponse{Message: req.Message}, nil } @@ -56,10 +64,10 @@ func main() { s := grpc.NewServer() // Register Greeter on the server. - hwpb.RegisterGreeterService(s, &hwpb.GreeterService{SayHello: sayHello}) + hwpb.RegisterGreeterServer(s, &hwServer{}) // Register RouteGuide on the same server. - ecpb.RegisterEchoService(s, &ecpb.EchoService{UnaryEcho: unaryEcho}) + ecpb.RegisterEchoServer(s, &ecServer{}) // Register reflection service on gRPC server. reflection.Register(s) diff --git a/examples/features/retry/server/main.go b/examples/features/retry/server/main.go index 08dd40c93f1..fdec2f052e2 100644 --- a/examples/features/retry/server/main.go +++ b/examples/features/retry/server/main.go @@ -37,6 +37,7 @@ import ( var port = flag.Int("port", 50052, "port number") type failingServer struct { + pb.UnimplementedEchoServer mu sync.Mutex reqCounter uint @@ -85,7 +86,7 @@ func main() { reqModulo: 4, } - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: failingservice.UnaryEcho}) + pb.RegisterEchoServer(s, failingservice) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } diff --git a/examples/features/wait_for_ready/main.go b/examples/features/wait_for_ready/main.go index f3669e98657..f865410f1aa 100644 --- a/examples/features/wait_for_ready/main.go +++ b/examples/features/wait_for_ready/main.go @@ -34,7 +34,12 @@ import ( pb "google.golang.org/grpc/examples/features/proto/echo" ) -func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { +// server is used to implement EchoServer. +type server struct { + pb.UnimplementedEchoServer +} + +func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { return &pb.EchoResponse{Message: req.Message}, nil } @@ -45,7 +50,7 @@ func serve() { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) + pb.RegisterEchoServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/xds/server/main.go b/examples/features/xds/server/main.go index 96cd6e468cf..7e0815645e5 100644 --- a/examples/features/xds/server/main.go +++ b/examples/features/xds/server/main.go @@ -45,6 +45,8 @@ const ( // server is used to implement helloworld.GreeterServer. type server struct { + pb.UnimplementedGreeterServer + serverName string } @@ -122,8 +124,7 @@ func main() { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - hw := newServer(hostname) - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: hw.SayHello}) + pb.RegisterGreeterServer(s, newServer(hostname)) reflection.Register(s) healthServer := health.NewServer() diff --git a/examples/gotutorial.md b/examples/gotutorial.md index 2862b0a28b9..86993562e90 100644 --- a/examples/gotutorial.md +++ b/examples/gotutorial.md @@ -268,13 +268,7 @@ if err != nil { log.Fatalf("failed to listen: %v", err) } grpcServer := grpc.NewServer() -rgs := &routeGuideServer{} -pb.RegisterRouteGuideService(grpcServer, pb.RouteGuideService{ - GetFeature: rgs.GetFeature, - ListFeatures: rgs.ListFeatures, - RecordRoute: rgs.RecordRoute, - RouteChat: rgs.RouteChat, -}) +pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{}) ... // determine whether to use TLS grpcServer.Serve(lis) ``` diff --git a/examples/helloworld/greeter_server/main.go b/examples/helloworld/greeter_server/main.go index 4406f42011e..15604f9fc1f 100644 --- a/examples/helloworld/greeter_server/main.go +++ b/examples/helloworld/greeter_server/main.go @@ -32,8 +32,13 @@ const ( port = ":50051" ) -// sayHello implements helloworld.GreeterServer.SayHello -func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { +// server is used to implement helloworld.GreeterServer. +type server struct { + pb.UnimplementedGreeterServer +} + +// SayHello implements helloworld.GreeterServer +func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v", in.GetName()) return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil } @@ -44,7 +49,7 @@ func main() { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) + pb.RegisterGreeterServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } diff --git a/examples/helloworld/helloworld/helloworld_grpc.pb.go b/examples/helloworld/helloworld/helloworld_grpc.pb.go index 78d60253a6d..2608e4acda9 100644 --- a/examples/helloworld/helloworld/helloworld_grpc.pb.go +++ b/examples/helloworld/helloworld/helloworld_grpc.pb.go @@ -29,10 +29,6 @@ func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { return &greeterClient{cc} } -var greeterSayHelloStreamDesc = &grpc.StreamDesc{ - StreamName: "SayHello", -} - func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { out := new(HelloReply) err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) @@ -42,52 +38,62 @@ func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ... return out, nil } -// GreeterService is the service API for Greeter service. -// Fields should be assigned to their respective handler implementations only before -// RegisterGreeterService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type GreeterService struct { +// GreeterServer is the server API for Greeter service. +// All implementations must embed UnimplementedGreeterServer +// for forward compatibility +type GreeterServer interface { // Sends a greeting - SayHello func(context.Context, *HelloRequest) (*HelloReply, error) + SayHello(context.Context, *HelloRequest) (*HelloReply, error) + mustEmbedUnimplementedGreeterServer() +} + +// UnimplementedGreeterServer must be embedded to have forward compatible implementations. +type UnimplementedGreeterServer struct { } -func (s *GreeterService) sayHello(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { + return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") +} +func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} + +// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to GreeterServer will +// result in compilation errors. +type UnsafeGreeterServer interface { + mustEmbedUnimplementedGreeterServer() +} + +func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { + s.RegisterService(&_Greeter_serviceDesc, srv) +} + +func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HelloRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.SayHello(ctx, in) + return srv.(GreeterServer).SayHello(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/helloworld.Greeter/SayHello", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.SayHello(ctx, req.(*HelloRequest)) + return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterGreeterService registers a service implementation with a gRPC server. -func RegisterGreeterService(s grpc.ServiceRegistrar, srv *GreeterService) { - srvCopy := *srv - if srvCopy.SayHello == nil { - srvCopy.SayHello = func(context.Context, *HelloRequest) (*HelloReply, error) { - return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "helloworld.Greeter", - Methods: []grpc.MethodDesc{ - { - MethodName: "SayHello", - Handler: srvCopy.sayHello, - }, +var _Greeter_serviceDesc = grpc.ServiceDesc{ + ServiceName: "helloworld.Greeter", + HandlerType: (*GreeterServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "SayHello", + Handler: _Greeter_SayHello_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/helloworld/helloworld/helloworld.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{}, + Metadata: "examples/helloworld/helloworld/helloworld.proto", } diff --git a/examples/route_guide/routeguide/route_guide_grpc.pb.go b/examples/route_guide/routeguide/route_guide_grpc.pb.go index bbcfe7daea3..3c11b121a54 100644 --- a/examples/route_guide/routeguide/route_guide_grpc.pb.go +++ b/examples/route_guide/routeguide/route_guide_grpc.pb.go @@ -51,10 +51,6 @@ func NewRouteGuideClient(cc grpc.ClientConnInterface) RouteGuideClient { return &routeGuideClient{cc} } -var routeGuideGetFeatureStreamDesc = &grpc.StreamDesc{ - StreamName: "GetFeature", -} - func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) { out := new(Feature) err := c.cc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, opts...) @@ -64,13 +60,8 @@ func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...gr return out, nil } -var routeGuideListFeaturesStreamDesc = &grpc.StreamDesc{ - StreamName: "ListFeatures", - ServerStreams: true, -} - func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) { - stream, err := c.cc.NewStream(ctx, routeGuideListFeaturesStreamDesc, "/routeguide.RouteGuide/ListFeatures", opts...) + stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[0], "/routeguide.RouteGuide/ListFeatures", opts...) if err != nil { return nil, err } @@ -101,13 +92,8 @@ func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) { return m, nil } -var routeGuideRecordRouteStreamDesc = &grpc.StreamDesc{ - StreamName: "RecordRoute", - ClientStreams: true, -} - func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) { - stream, err := c.cc.NewStream(ctx, routeGuideRecordRouteStreamDesc, "/routeguide.RouteGuide/RecordRoute", opts...) + stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[1], "/routeguide.RouteGuide/RecordRoute", opts...) if err != nil { return nil, err } @@ -140,14 +126,8 @@ func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) { return m, nil } -var routeGuideRouteChatStreamDesc = &grpc.StreamDesc{ - StreamName: "RouteChat", - ServerStreams: true, - ClientStreams: true, -} - func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) { - stream, err := c.cc.NewStream(ctx, routeGuideRouteChatStreamDesc, "/routeguide.RouteGuide/RouteChat", opts...) + stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[2], "/routeguide.RouteGuide/RouteChat", opts...) if err != nil { return nil, err } @@ -177,66 +157,90 @@ func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) { return m, nil } -// RouteGuideService is the service API for RouteGuide service. -// Fields should be assigned to their respective handler implementations only before -// RegisterRouteGuideService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type RouteGuideService struct { +// RouteGuideServer is the server API for RouteGuide service. +// All implementations must embed UnimplementedRouteGuideServer +// for forward compatibility +type RouteGuideServer interface { // A simple RPC. // // Obtains the feature at a given position. // // A feature with an empty name is returned if there's no feature at the given // position. - GetFeature func(context.Context, *Point) (*Feature, error) + GetFeature(context.Context, *Point) (*Feature, error) // A server-to-client streaming RPC. // // Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a // repeated field), as the rectangle may cover a large area and contain a // huge number of features. - ListFeatures func(*Rectangle, RouteGuide_ListFeaturesServer) error + ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error // A client-to-server streaming RPC. // // Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. - RecordRoute func(RouteGuide_RecordRouteServer) error + RecordRoute(RouteGuide_RecordRouteServer) error // A Bidirectional streaming RPC. // // Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). - RouteChat func(RouteGuide_RouteChatServer) error + RouteChat(RouteGuide_RouteChatServer) error + mustEmbedUnimplementedRouteGuideServer() +} + +// UnimplementedRouteGuideServer must be embedded to have forward compatible implementations. +type UnimplementedRouteGuideServer struct { +} + +func (UnimplementedRouteGuideServer) GetFeature(context.Context, *Point) (*Feature, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetFeature not implemented") +} +func (UnimplementedRouteGuideServer) ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error { + return status.Errorf(codes.Unimplemented, "method ListFeatures not implemented") +} +func (UnimplementedRouteGuideServer) RecordRoute(RouteGuide_RecordRouteServer) error { + return status.Errorf(codes.Unimplemented, "method RecordRoute not implemented") +} +func (UnimplementedRouteGuideServer) RouteChat(RouteGuide_RouteChatServer) error { + return status.Errorf(codes.Unimplemented, "method RouteChat not implemented") +} +func (UnimplementedRouteGuideServer) mustEmbedUnimplementedRouteGuideServer() {} + +// UnsafeRouteGuideServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to RouteGuideServer will +// result in compilation errors. +type UnsafeRouteGuideServer interface { + mustEmbedUnimplementedRouteGuideServer() } -func (s *RouteGuideService) getFeature(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) { + s.RegisterService(&_RouteGuide_serviceDesc, srv) +} + +func _RouteGuide_GetFeature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Point) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetFeature(ctx, in) + return srv.(RouteGuideServer).GetFeature(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/routeguide.RouteGuide/GetFeature", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetFeature(ctx, req.(*Point)) + return srv.(RouteGuideServer).GetFeature(ctx, req.(*Point)) } return interceptor(ctx, in, info, handler) } -func (s *RouteGuideService) listFeatures(_ interface{}, stream grpc.ServerStream) error { + +func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(Rectangle) if err := stream.RecvMsg(m); err != nil { return err } - return s.ListFeatures(m, &routeGuideListFeaturesServer{stream}) -} -func (s *RouteGuideService) recordRoute(_ interface{}, stream grpc.ServerStream) error { - return s.RecordRoute(&routeGuideRecordRouteServer{stream}) -} -func (s *RouteGuideService) routeChat(_ interface{}, stream grpc.ServerStream) error { - return s.RouteChat(&routeGuideRouteChatServer{stream}) + return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream}) } type RouteGuide_ListFeaturesServer interface { @@ -252,6 +256,10 @@ func (x *routeGuideListFeaturesServer) Send(m *Feature) error { return x.ServerStream.SendMsg(m) } +func _RouteGuide_RecordRoute_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(RouteGuideServer).RecordRoute(&routeGuideRecordRouteServer{stream}) +} + type RouteGuide_RecordRouteServer interface { SendAndClose(*RouteSummary) error Recv() (*Point, error) @@ -274,6 +282,10 @@ func (x *routeGuideRecordRouteServer) Recv() (*Point, error) { return m, nil } +func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream}) +} + type RouteGuide_RouteChatServer interface { Send(*RouteNote) error Recv() (*RouteNote, error) @@ -296,57 +308,32 @@ func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) { return m, nil } -// RegisterRouteGuideService registers a service implementation with a gRPC server. -func RegisterRouteGuideService(s grpc.ServiceRegistrar, srv *RouteGuideService) { - srvCopy := *srv - if srvCopy.GetFeature == nil { - srvCopy.GetFeature = func(context.Context, *Point) (*Feature, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetFeature not implemented") - } - } - if srvCopy.ListFeatures == nil { - srvCopy.ListFeatures = func(*Rectangle, RouteGuide_ListFeaturesServer) error { - return status.Errorf(codes.Unimplemented, "method ListFeatures not implemented") - } - } - if srvCopy.RecordRoute == nil { - srvCopy.RecordRoute = func(RouteGuide_RecordRouteServer) error { - return status.Errorf(codes.Unimplemented, "method RecordRoute not implemented") - } - } - if srvCopy.RouteChat == nil { - srvCopy.RouteChat = func(RouteGuide_RouteChatServer) error { - return status.Errorf(codes.Unimplemented, "method RouteChat not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "routeguide.RouteGuide", - Methods: []grpc.MethodDesc{ - { - MethodName: "GetFeature", - Handler: srvCopy.getFeature, - }, +var _RouteGuide_serviceDesc = grpc.ServiceDesc{ + ServiceName: "routeguide.RouteGuide", + HandlerType: (*RouteGuideServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetFeature", + Handler: _RouteGuide_GetFeature_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "ListFeatures", - Handler: srvCopy.listFeatures, - ServerStreams: true, - }, - { - StreamName: "RecordRoute", - Handler: srvCopy.recordRoute, - ClientStreams: true, - }, - { - StreamName: "RouteChat", - Handler: srvCopy.routeChat, - ServerStreams: true, - ClientStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "ListFeatures", + Handler: _RouteGuide_ListFeatures_Handler, + ServerStreams: true, }, - Metadata: "examples/route_guide/routeguide/route_guide.proto", - } - - s.RegisterService(&sd, nil) + { + StreamName: "RecordRoute", + Handler: _RouteGuide_RecordRoute_Handler, + ClientStreams: true, + }, + { + StreamName: "RouteChat", + Handler: _RouteGuide_RouteChat_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "examples/route_guide/routeguide/route_guide.proto", } diff --git a/examples/route_guide/server/server.go b/examples/route_guide/server/server.go index 3c0775e76f5..dd804406afc 100644 --- a/examples/route_guide/server/server.go +++ b/examples/route_guide/server/server.go @@ -54,21 +54,13 @@ var ( ) type routeGuideServer struct { + pb.UnimplementedRouteGuideServer savedFeatures []*pb.Feature // read-only after initialized mu sync.Mutex // protects routeNotes routeNotes map[string][]*pb.RouteNote } -func (s *routeGuideServer) Svc() *pb.RouteGuideService { - return &pb.RouteGuideService{ - GetFeature: s.GetFeature, - ListFeatures: s.ListFeatures, - RecordRoute: s.RecordRoute, - RouteChat: s.RouteChat, - } -} - // GetFeature returns the feature at the given point. func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { for _, feature := range s.savedFeatures { @@ -246,7 +238,7 @@ func main() { opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) - pb.RegisterRouteGuideService(grpcServer, newServer().Svc()) + pb.RegisterRouteGuideServer(grpcServer, newServer()) grpcServer.Serve(lis) } diff --git a/health/grpc_health_v1/health_grpc.pb.go b/health/grpc_health_v1/health_grpc.pb.go index e7fda8735b2..463c8734ade 100644 --- a/health/grpc_health_v1/health_grpc.pb.go +++ b/health/grpc_health_v1/health_grpc.pb.go @@ -46,10 +46,6 @@ func NewHealthClient(cc grpc.ClientConnInterface) HealthClient { return &healthClient{cc} } -var healthCheckStreamDesc = &grpc.StreamDesc{ - StreamName: "Check", -} - func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { out := new(HealthCheckResponse) err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) @@ -59,13 +55,8 @@ func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts . return out, nil } -var healthWatchStreamDesc = &grpc.StreamDesc{ - StreamName: "Watch", - ServerStreams: true, -} - func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, healthWatchStreamDesc, "/grpc.health.v1.Health/Watch", opts...) + stream, err := c.cc.NewStream(ctx, &_Health_serviceDesc.Streams[0], "/grpc.health.v1.Health/Watch", opts...) if err != nil { return nil, err } @@ -96,14 +87,13 @@ func (x *healthWatchClient) Recv() (*HealthCheckResponse, error) { return m, nil } -// HealthService is the service API for Health service. -// Fields should be assigned to their respective handler implementations only before -// RegisterHealthService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type HealthService struct { +// HealthServer is the server API for Health service. +// All implementations should embed UnimplementedHealthServer +// for forward compatibility +type HealthServer interface { // If the requested service is unknown, the call will fail with status // NOT_FOUND. - Check func(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) + Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) // Performs a watch for the serving status of the requested service. // The server will immediately send back a message indicating the current // serving status. It will then subsequently send a new message whenever @@ -119,32 +109,55 @@ type HealthService struct { // should assume this method is not supported and should not retry the // call. If the call terminates with any other status (including OK), // clients should retry the call with appropriate exponential backoff. - Watch func(*HealthCheckRequest, Health_WatchServer) error + Watch(*HealthCheckRequest, Health_WatchServer) error +} + +// UnimplementedHealthServer should be embedded to have forward compatible implementations. +type UnimplementedHealthServer struct { } -func (s *HealthService) check(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func (UnimplementedHealthServer) Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") +} +func (UnimplementedHealthServer) Watch(*HealthCheckRequest, Health_WatchServer) error { + return status.Errorf(codes.Unimplemented, "method Watch not implemented") +} + +// UnsafeHealthServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to HealthServer will +// result in compilation errors. +type UnsafeHealthServer interface { + mustEmbedUnimplementedHealthServer() +} + +func RegisterHealthServer(s *grpc.Server, srv HealthServer) { + s.RegisterService(&_Health_serviceDesc, srv) +} + +func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HealthCheckRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.Check(ctx, in) + return srv.(HealthServer).Check(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.health.v1.Health/Check", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.Check(ctx, req.(*HealthCheckRequest)) + return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) } return interceptor(ctx, in, info, handler) } -func (s *HealthService) watch(_ interface{}, stream grpc.ServerStream) error { + +func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(HealthCheckRequest) if err := stream.RecvMsg(m); err != nil { return err } - return s.Watch(m, &healthWatchServer{stream}) + return srv.(HealthServer).Watch(m, &healthWatchServer{stream}) } type Health_WatchServer interface { @@ -160,83 +173,21 @@ func (x *healthWatchServer) Send(m *HealthCheckResponse) error { return x.ServerStream.SendMsg(m) } -// RegisterHealthService registers a service implementation with a gRPC server. -func RegisterHealthService(s grpc.ServiceRegistrar, srv *HealthService) { - srvCopy := *srv - if srvCopy.Check == nil { - srvCopy.Check = func(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") - } - } - if srvCopy.Watch == nil { - srvCopy.Watch = func(*HealthCheckRequest, Health_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.health.v1.Health", - Methods: []grpc.MethodDesc{ - { - MethodName: "Check", - Handler: srvCopy.check, - }, +var _Health_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.health.v1.Health", + HandlerType: (*HealthServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Check", + Handler: _Health_Check_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: srvCopy.watch, - ServerStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Watch", + Handler: _Health_Watch_Handler, + ServerStreams: true, }, - Metadata: "grpc/health/v1/health.proto", - } - - s.RegisterService(&sd, nil) -} - -// HealthServer is the service API for Health service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type HealthServer interface { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. - Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - Watch(*HealthCheckRequest, Health_WatchServer) error -} - -// UnimplementedHealthServer can be embedded to have forward compatible implementations of -// HealthServer -type UnimplementedHealthServer struct { -} - -func (UnimplementedHealthServer) Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") -} -func (UnimplementedHealthServer) Watch(*HealthCheckRequest, Health_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} - -// RegisterHealthServer registers a service implementation with a gRPC server. -func RegisterHealthServer(s grpc.ServiceRegistrar, srv HealthServer) { - str := &HealthService{ - Check: srv.Check, - Watch: srv.Watch, - } - RegisterHealthService(s, str) + }, + Metadata: "grpc/health/v1/health.proto", } diff --git a/interop/alts/server/server.go b/interop/alts/server/server.go index 0ac7678a51b..0d0f375a0d1 100644 --- a/interop/alts/server/server.go +++ b/interop/alts/server/server.go @@ -64,7 +64,7 @@ func main() { } altsTC := alts.NewServerCreds(opts) grpcServer := grpc.NewServer(grpc.Creds(altsTC), grpc.InTapHandle(authz)) - testpb.RegisterTestServiceService(grpcServer, interop.NewTestServer()) + testpb.RegisterTestServiceServer(grpcServer, interop.NewTestServer()) grpcServer.Serve(lis) } diff --git a/interop/grpc_testing/test_grpc.pb.go b/interop/grpc_testing/test_grpc.pb.go index e158bb4b20d..f1b3bfb6c8b 100644 --- a/interop/grpc_testing/test_grpc.pb.go +++ b/interop/grpc_testing/test_grpc.pb.go @@ -47,10 +47,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient { return &testServiceClient{cc} } -var testServiceEmptyCallStreamDesc = &grpc.StreamDesc{ - StreamName: "EmptyCall", -} - func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { out := new(Empty) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) @@ -60,10 +56,6 @@ func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...gr return out, nil } -var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnaryCall", -} - func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { out := new(SimpleResponse) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) @@ -73,13 +65,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op return out, nil } -var testServiceStreamingOutputCallStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingOutputCall", - ServerStreams: true, -} - func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceStreamingOutputCallStreamDesc, "/grpc.testing.TestService/StreamingOutputCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...) if err != nil { return nil, err } @@ -110,13 +97,8 @@ func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallRespo return m, nil } -var testServiceStreamingInputCallStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingInputCall", - ClientStreams: true, -} - func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceStreamingInputCallStreamDesc, "/grpc.testing.TestService/StreamingInputCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...) if err != nil { return nil, err } @@ -149,14 +131,8 @@ func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCal return m, nil } -var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{ - StreamName: "FullDuplexCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...) if err != nil { return nil, err } @@ -186,14 +162,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, return m, nil } -var testServiceHalfDuplexCallStreamDesc = &grpc.StreamDesc{ - StreamName: "HalfDuplexCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceHalfDuplexCallStreamDesc, "/grpc.testing.TestService/HalfDuplexCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...) if err != nil { return nil, err } @@ -223,82 +193,110 @@ func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, return m, nil } -// TestServiceService is the service API for TestService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterTestServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type TestServiceService struct { +// TestServiceServer is the server API for TestService service. +// All implementations must embed UnimplementedTestServiceServer +// for forward compatibility +type TestServiceServer interface { // One empty request followed by one empty response. - EmptyCall func(context.Context, *Empty) (*Empty, error) + EmptyCall(context.Context, *Empty) (*Empty, error) // One request followed by one response. // The server returns the client payload as-is. - UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) + UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) // One request followed by a sequence of responses (streamed download). // The server returns the payload with client desired type and sizes. - StreamingOutputCall func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error + StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error // A sequence of requests followed by one response (streamed upload). // The server returns the aggregated size of client payload as the result. - StreamingInputCall func(TestService_StreamingInputCallServer) error + StreamingInputCall(TestService_StreamingInputCallServer) error // A sequence of requests with each request served by the server immediately. // As one request could lead to multiple responses, this interface // demonstrates the idea of full duplexing. - FullDuplexCall func(TestService_FullDuplexCallServer) error + FullDuplexCall(TestService_FullDuplexCallServer) error // A sequence of requests followed by a sequence of responses. // The server buffers all the client requests and then serves them in order. A // stream of responses are returned to the client when the server starts with // first request. - HalfDuplexCall func(TestService_HalfDuplexCallServer) error + HalfDuplexCall(TestService_HalfDuplexCallServer) error + mustEmbedUnimplementedTestServiceServer() +} + +// UnimplementedTestServiceServer must be embedded to have forward compatible implementations. +type UnimplementedTestServiceServer struct { +} + +func (UnimplementedTestServiceServer) EmptyCall(context.Context, *Empty) (*Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") +} +func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") } +func (UnimplementedTestServiceServer) StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented") +} +func (UnimplementedTestServiceServer) StreamingInputCall(TestService_StreamingInputCallServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented") +} +func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error { + return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") +} +func (UnimplementedTestServiceServer) HalfDuplexCall(TestService_HalfDuplexCallServer) error { + return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented") +} +func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {} -func (s *TestServiceService) emptyCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to TestServiceServer will +// result in compilation errors. +type UnsafeTestServiceServer interface { + mustEmbedUnimplementedTestServiceServer() +} + +func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { + s.RegisterService(&_TestService_serviceDesc, srv) +} + +func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.EmptyCall(ctx, in) + return srv.(TestServiceServer).EmptyCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.TestService/EmptyCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.EmptyCall(ctx, req.(*Empty)) + return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) } return interceptor(ctx, in, info, handler) } -func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnaryCall(ctx, in) + return srv.(TestServiceServer).UnaryCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.TestService/UnaryCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnaryCall(ctx, req.(*SimpleRequest)) + return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) } return interceptor(ctx, in, info, handler) } -func (s *TestServiceService) streamingOutputCall(_ interface{}, stream grpc.ServerStream) error { + +func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(StreamingOutputCallRequest) if err := stream.RecvMsg(m); err != nil { return err } - return s.StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} -func (s *TestServiceService) streamingInputCall(_ interface{}, stream grpc.ServerStream) error { - return s.StreamingInputCall(&testServiceStreamingInputCallServer{stream}) -} -func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error { - return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} -func (s *TestServiceService) halfDuplexCall(_ interface{}, stream grpc.ServerStream) error { - return s.HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) + return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) } type TestService_StreamingOutputCallServer interface { @@ -314,6 +312,10 @@ func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallRespon return x.ServerStream.SendMsg(m) } +func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream}) +} + type TestService_StreamingInputCallServer interface { SendAndClose(*StreamingInputCallResponse) error Recv() (*StreamingInputCallRequest, error) @@ -336,6 +338,10 @@ func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest return m, nil } +func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) +} + type TestService_FullDuplexCallServer interface { Send(*StreamingOutputCallResponse) error Recv() (*StreamingOutputCallRequest, error) @@ -358,6 +364,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, e return m, nil } +func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) +} + type TestService_HalfDuplexCallServer interface { Send(*StreamingOutputCallResponse) error Recv() (*StreamingOutputCallRequest, error) @@ -380,79 +390,44 @@ func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, e return m, nil } -// RegisterTestServiceService registers a service implementation with a gRPC server. -func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { - srvCopy := *srv - if srvCopy.EmptyCall == nil { - srvCopy.EmptyCall = func(context.Context, *Empty) (*Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") - } - } - if srvCopy.UnaryCall == nil { - srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") - } - } - if srvCopy.StreamingOutputCall == nil { - srvCopy.StreamingOutputCall = func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented") - } - } - if srvCopy.StreamingInputCall == nil { - srvCopy.StreamingInputCall = func(TestService_StreamingInputCallServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented") - } - } - if srvCopy.FullDuplexCall == nil { - srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error { - return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") - } - } - if srvCopy.HalfDuplexCall == nil { - srvCopy.HalfDuplexCall = func(TestService_HalfDuplexCallServer) error { - return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: srvCopy.emptyCall, - }, - { - MethodName: "UnaryCall", - Handler: srvCopy.unaryCall, - }, +var _TestService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.TestService", + HandlerType: (*TestServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "EmptyCall", + Handler: _TestService_EmptyCall_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingOutputCall", - Handler: srvCopy.streamingOutputCall, - ServerStreams: true, - }, - { - StreamName: "StreamingInputCall", - Handler: srvCopy.streamingInputCall, - ClientStreams: true, - }, - { - StreamName: "FullDuplexCall", - Handler: srvCopy.fullDuplexCall, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "HalfDuplexCall", - Handler: srvCopy.halfDuplexCall, - ServerStreams: true, - ClientStreams: true, - }, + { + MethodName: "UnaryCall", + Handler: _TestService_UnaryCall_Handler, }, - Metadata: "interop/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "StreamingOutputCall", + Handler: _TestService_StreamingOutputCall_Handler, + ServerStreams: true, + }, + { + StreamName: "StreamingInputCall", + Handler: _TestService_StreamingInputCall_Handler, + ClientStreams: true, + }, + { + StreamName: "FullDuplexCall", + Handler: _TestService_FullDuplexCall_Handler, + ServerStreams: true, + ClientStreams: true, + }, + { + StreamName: "HalfDuplexCall", + Handler: _TestService_HalfDuplexCall_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "interop/grpc_testing/test.proto", } // UnimplementedServiceClient is the client API for UnimplementedService service. @@ -471,10 +446,6 @@ func NewUnimplementedServiceClient(cc grpc.ClientConnInterface) UnimplementedSer return &unimplementedServiceClient{cc} } -var unimplementedServiceUnimplementedCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnimplementedCall", -} - func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { out := new(Empty) err := c.cc.Invoke(ctx, "/grpc.testing.UnimplementedService/UnimplementedCall", in, out, opts...) @@ -484,54 +455,64 @@ func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in * return out, nil } -// UnimplementedServiceService is the service API for UnimplementedService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterUnimplementedServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type UnimplementedServiceService struct { +// UnimplementedServiceServer is the server API for UnimplementedService service. +// All implementations must embed UnimplementedUnimplementedServiceServer +// for forward compatibility +type UnimplementedServiceServer interface { // A call that no server should implement - UnimplementedCall func(context.Context, *Empty) (*Empty, error) + UnimplementedCall(context.Context, *Empty) (*Empty, error) + mustEmbedUnimplementedUnimplementedServiceServer() +} + +// UnimplementedUnimplementedServiceServer must be embedded to have forward compatible implementations. +type UnimplementedUnimplementedServiceServer struct { +} + +func (UnimplementedUnimplementedServiceServer) UnimplementedCall(context.Context, *Empty) (*Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnimplementedCall not implemented") +} +func (UnimplementedUnimplementedServiceServer) mustEmbedUnimplementedUnimplementedServiceServer() {} + +// UnsafeUnimplementedServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to UnimplementedServiceServer will +// result in compilation errors. +type UnsafeUnimplementedServiceServer interface { + mustEmbedUnimplementedUnimplementedServiceServer() } -func (s *UnimplementedServiceService) unimplementedCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterUnimplementedServiceServer(s *grpc.Server, srv UnimplementedServiceServer) { + s.RegisterService(&_UnimplementedService_serviceDesc, srv) +} + +func _UnimplementedService_UnimplementedCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnimplementedCall(ctx, in) + return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.UnimplementedService/UnimplementedCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnimplementedCall(ctx, req.(*Empty)) + return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, req.(*Empty)) } return interceptor(ctx, in, info, handler) } -// RegisterUnimplementedServiceService registers a service implementation with a gRPC server. -func RegisterUnimplementedServiceService(s grpc.ServiceRegistrar, srv *UnimplementedServiceService) { - srvCopy := *srv - if srvCopy.UnimplementedCall == nil { - srvCopy.UnimplementedCall = func(context.Context, *Empty) (*Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnimplementedCall not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.UnimplementedService", - Methods: []grpc.MethodDesc{ - { - MethodName: "UnimplementedCall", - Handler: srvCopy.unimplementedCall, - }, +var _UnimplementedService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.UnimplementedService", + HandlerType: (*UnimplementedServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UnimplementedCall", + Handler: _UnimplementedService_UnimplementedCall_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "interop/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{}, + Metadata: "interop/grpc_testing/test.proto", } // LoadBalancerStatsServiceClient is the client API for LoadBalancerStatsService service. @@ -550,10 +531,6 @@ func NewLoadBalancerStatsServiceClient(cc grpc.ClientConnInterface) LoadBalancer return &loadBalancerStatsServiceClient{cc} } -var loadBalancerStatsServiceGetClientStatsStreamDesc = &grpc.StreamDesc{ - StreamName: "GetClientStats", -} - func (c *loadBalancerStatsServiceClient) GetClientStats(ctx context.Context, in *LoadBalancerStatsRequest, opts ...grpc.CallOption) (*LoadBalancerStatsResponse, error) { out := new(LoadBalancerStatsResponse) err := c.cc.Invoke(ctx, "/grpc.testing.LoadBalancerStatsService/GetClientStats", in, out, opts...) @@ -563,52 +540,63 @@ func (c *loadBalancerStatsServiceClient) GetClientStats(ctx context.Context, in return out, nil } -// LoadBalancerStatsServiceService is the service API for LoadBalancerStatsService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterLoadBalancerStatsServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type LoadBalancerStatsServiceService struct { +// LoadBalancerStatsServiceServer is the server API for LoadBalancerStatsService service. +// All implementations must embed UnimplementedLoadBalancerStatsServiceServer +// for forward compatibility +type LoadBalancerStatsServiceServer interface { // Gets the backend distribution for RPCs sent by a test client. - GetClientStats func(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) + GetClientStats(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) + mustEmbedUnimplementedLoadBalancerStatsServiceServer() +} + +// UnimplementedLoadBalancerStatsServiceServer must be embedded to have forward compatible implementations. +type UnimplementedLoadBalancerStatsServiceServer struct { +} + +func (UnimplementedLoadBalancerStatsServiceServer) GetClientStats(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetClientStats not implemented") +} +func (UnimplementedLoadBalancerStatsServiceServer) mustEmbedUnimplementedLoadBalancerStatsServiceServer() { +} + +// UnsafeLoadBalancerStatsServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LoadBalancerStatsServiceServer will +// result in compilation errors. +type UnsafeLoadBalancerStatsServiceServer interface { + mustEmbedUnimplementedLoadBalancerStatsServiceServer() } -func (s *LoadBalancerStatsServiceService) getClientStats(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterLoadBalancerStatsServiceServer(s *grpc.Server, srv LoadBalancerStatsServiceServer) { + s.RegisterService(&_LoadBalancerStatsService_serviceDesc, srv) +} + +func _LoadBalancerStatsService_GetClientStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LoadBalancerStatsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetClientStats(ctx, in) + return srv.(LoadBalancerStatsServiceServer).GetClientStats(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.LoadBalancerStatsService/GetClientStats", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetClientStats(ctx, req.(*LoadBalancerStatsRequest)) + return srv.(LoadBalancerStatsServiceServer).GetClientStats(ctx, req.(*LoadBalancerStatsRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterLoadBalancerStatsServiceService registers a service implementation with a gRPC server. -func RegisterLoadBalancerStatsServiceService(s grpc.ServiceRegistrar, srv *LoadBalancerStatsServiceService) { - srvCopy := *srv - if srvCopy.GetClientStats == nil { - srvCopy.GetClientStats = func(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetClientStats not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.LoadBalancerStatsService", - Methods: []grpc.MethodDesc{ - { - MethodName: "GetClientStats", - Handler: srvCopy.getClientStats, - }, +var _LoadBalancerStatsService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.LoadBalancerStatsService", + HandlerType: (*LoadBalancerStatsServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetClientStats", + Handler: _LoadBalancerStatsService_GetClientStats_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "interop/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{}, + Metadata: "interop/grpc_testing/test.proto", } diff --git a/interop/server/server.go b/interop/server/server.go index 662fb296309..c70e450bb10 100644 --- a/interop/server/server.go +++ b/interop/server/server.go @@ -76,6 +76,6 @@ func main() { opts = append(opts, grpc.Creds(altsTC)) } server := grpc.NewServer(opts...) - testpb.RegisterTestServiceService(server, interop.NewTestServer()) + testpb.RegisterTestServiceServer(server, interop.NewTestServer()) server.Serve(lis) } diff --git a/interop/test_utils.go b/interop/test_utils.go index dd2a73155e6..7e3aaa95f0c 100644 --- a/interop/test_utils.go +++ b/interop/test_utils.go @@ -673,19 +673,13 @@ func DoPickFirstUnary(tc testpb.TestServiceClient) { } } -type testServer struct{} +type testServer struct { + testpb.UnimplementedTestServiceServer +} // NewTestServer creates a test server for test service. -func NewTestServer() *testpb.TestServiceService { - s := testServer{} - return &testpb.TestServiceService{ - EmptyCall: s.EmptyCall, - UnaryCall: s.UnaryCall, - StreamingOutputCall: s.StreamingOutputCall, - StreamingInputCall: s.StreamingInputCall, - FullDuplexCall: s.FullDuplexCall, - HalfDuplexCall: s.HalfDuplexCall, - } +func NewTestServer() testpb.TestServiceServer { + return &testServer{} } func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { diff --git a/interop/xds/client/client.go b/interop/xds/client/client.go index 46621906388..b119bcd2b86 100644 --- a/interop/xds/client/client.go +++ b/interop/xds/client/client.go @@ -95,6 +95,10 @@ var ( logger = grpclog.Component("interop") ) +type statsService struct { + testpb.UnimplementedLoadBalancerStatsServiceServer +} + func hasRPCSucceeded() bool { return atomic.LoadUint32(&rpcSucceeded) > 0 } @@ -107,7 +111,7 @@ func setRPCSucceeded() { // and return the distribution of remote peers. This is essentially a clientside // LB reporting mechanism that is designed to be queried by an external test // driver when verifying that the client is distributing RPCs as expected. -func getClientStats(ctx context.Context, in *testpb.LoadBalancerStatsRequest) (*testpb.LoadBalancerStatsResponse, error) { +func (s *statsService) GetClientStats(ctx context.Context, in *testpb.LoadBalancerStatsRequest) (*testpb.LoadBalancerStatsResponse, error) { mu.Lock() watcherKey := statsWatcherKey{currentRequestID, currentRequestID + in.GetNumRpcs()} watcher, ok := watchers[watcherKey] @@ -222,7 +226,7 @@ func main() { } s := grpc.NewServer() defer s.Stop() - testpb.RegisterLoadBalancerStatsServiceService(s, &testpb.LoadBalancerStatsServiceService{GetClientStats: getClientStats}) + testpb.RegisterLoadBalancerStatsServiceServer(s, &statsService{}) go s.Serve(lis) clients := make([]testpb.TestServiceClient, *numChannels) diff --git a/interop/xds/server/server.go b/interop/xds/server/server.go index 8d2a62487a8..45b8448822b 100644 --- a/interop/xds/server/server.go +++ b/interop/xds/server/server.go @@ -49,12 +49,16 @@ func getHostname() string { return hostname } -func emptyCall(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) { +type server struct { + testpb.UnimplementedTestServiceServer +} + +func (s *server) EmptyCall(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) { grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname)) return &testpb.Empty{}, nil } -func unaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { +func (s *server) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname)) return &testpb.SimpleResponse{ServerId: *serverID, Hostname: hostname}, nil } @@ -67,6 +71,6 @@ func main() { logger.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - testpb.RegisterTestServiceService(s, &testpb.TestServiceService{EmptyCall: emptyCall, UnaryCall: unaryCall}) + testpb.RegisterTestServiceServer(s, &server{}) s.Serve(lis) } diff --git a/profiling/proto/service_grpc.pb.go b/profiling/proto/service_grpc.pb.go index a1993dc3b81..a23453e009a 100644 --- a/profiling/proto/service_grpc.pb.go +++ b/profiling/proto/service_grpc.pb.go @@ -32,10 +32,6 @@ func NewProfilingClient(cc grpc.ClientConnInterface) ProfilingClient { return &profilingClient{cc} } -var profilingEnableStreamDesc = &grpc.StreamDesc{ - StreamName: "Enable", -} - func (c *profilingClient) Enable(ctx context.Context, in *EnableRequest, opts ...grpc.CallOption) (*EnableResponse, error) { out := new(EnableResponse) err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/Enable", in, out, opts...) @@ -45,10 +41,6 @@ func (c *profilingClient) Enable(ctx context.Context, in *EnableRequest, opts .. return out, nil } -var profilingGetStreamStatsStreamDesc = &grpc.StreamDesc{ - StreamName: "GetStreamStats", -} - func (c *profilingClient) GetStreamStats(ctx context.Context, in *GetStreamStatsRequest, opts ...grpc.CallOption) (*GetStreamStatsResponse, error) { out := new(GetStreamStatsResponse) err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats", in, out, opts...) @@ -58,114 +50,88 @@ func (c *profilingClient) GetStreamStats(ctx context.Context, in *GetStreamStats return out, nil } -// ProfilingService is the service API for Profiling service. -// Fields should be assigned to their respective handler implementations only before -// RegisterProfilingService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type ProfilingService struct { +// ProfilingServer is the server API for Profiling service. +// All implementations should embed UnimplementedProfilingServer +// for forward compatibility +type ProfilingServer interface { // Enable allows users to toggle profiling on and off remotely. - Enable func(context.Context, *EnableRequest) (*EnableResponse, error) + Enable(context.Context, *EnableRequest) (*EnableResponse, error) // GetStreamStats is used to retrieve an array of stream-level stats from a // gRPC client/server. - GetStreamStats func(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) + GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) +} + +// UnimplementedProfilingServer should be embedded to have forward compatible implementations. +type UnimplementedProfilingServer struct { +} + +func (UnimplementedProfilingServer) Enable(context.Context, *EnableRequest) (*EnableResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Enable not implemented") +} +func (UnimplementedProfilingServer) GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented") +} + +// UnsafeProfilingServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ProfilingServer will +// result in compilation errors. +type UnsafeProfilingServer interface { + mustEmbedUnimplementedProfilingServer() +} + +func RegisterProfilingServer(s *grpc.Server, srv ProfilingServer) { + s.RegisterService(&_Profiling_serviceDesc, srv) } -func (s *ProfilingService) enable(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _Profiling_Enable_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EnableRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.Enable(ctx, in) + return srv.(ProfilingServer).Enable(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.go.profiling.v1alpha.Profiling/Enable", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.Enable(ctx, req.(*EnableRequest)) + return srv.(ProfilingServer).Enable(ctx, req.(*EnableRequest)) } return interceptor(ctx, in, info, handler) } -func (s *ProfilingService) getStreamStats(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _Profiling_GetStreamStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetStreamStatsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.GetStreamStats(ctx, in) + return srv.(ProfilingServer).GetStreamStats(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetStreamStats(ctx, req.(*GetStreamStatsRequest)) + return srv.(ProfilingServer).GetStreamStats(ctx, req.(*GetStreamStatsRequest)) } return interceptor(ctx, in, info, handler) } -// RegisterProfilingService registers a service implementation with a gRPC server. -func RegisterProfilingService(s grpc.ServiceRegistrar, srv *ProfilingService) { - srvCopy := *srv - if srvCopy.Enable == nil { - srvCopy.Enable = func(context.Context, *EnableRequest) (*EnableResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enable not implemented") - } - } - if srvCopy.GetStreamStats == nil { - srvCopy.GetStreamStats = func(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.go.profiling.v1alpha.Profiling", - Methods: []grpc.MethodDesc{ - { - MethodName: "Enable", - Handler: srvCopy.enable, - }, - { - MethodName: "GetStreamStats", - Handler: srvCopy.getStreamStats, - }, +var _Profiling_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.go.profiling.v1alpha.Profiling", + HandlerType: (*ProfilingServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Enable", + Handler: _Profiling_Enable_Handler, }, - Streams: []grpc.StreamDesc{}, - Metadata: "profiling/proto/service.proto", - } - - s.RegisterService(&sd, nil) -} - -// ProfilingServer is the service API for Profiling service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type ProfilingServer interface { - // Enable allows users to toggle profiling on and off remotely. - Enable(context.Context, *EnableRequest) (*EnableResponse, error) - // GetStreamStats is used to retrieve an array of stream-level stats from a - // gRPC client/server. - GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) -} - -// UnimplementedProfilingServer can be embedded to have forward compatible implementations of -// ProfilingServer -type UnimplementedProfilingServer struct { -} - -func (UnimplementedProfilingServer) Enable(context.Context, *EnableRequest) (*EnableResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enable not implemented") -} -func (UnimplementedProfilingServer) GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented") -} - -// RegisterProfilingServer registers a service implementation with a gRPC server. -func RegisterProfilingServer(s grpc.ServiceRegistrar, srv ProfilingServer) { - str := &ProfilingService{ - Enable: srv.Enable, - GetStreamStats: srv.GetStreamStats, - } - RegisterProfilingService(s, str) + { + MethodName: "GetStreamStats", + Handler: _Profiling_GetStreamStats_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "profiling/proto/service.proto", } diff --git a/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go b/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go index 803e3a45ff6..47f2ea55298 100644 --- a/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go +++ b/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go @@ -30,14 +30,8 @@ func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClie return &serverReflectionClient{cc} } -var serverReflectionServerReflectionInfoStreamDesc = &grpc.StreamDesc{ - StreamName: "ServerReflectionInfo", - ServerStreams: true, - ClientStreams: true, -} - func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { - stream, err := c.cc.NewStream(ctx, serverReflectionServerReflectionInfoStreamDesc, "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) + stream, err := c.cc.NewStream(ctx, &_ServerReflection_serviceDesc.Streams[0], "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) if err != nil { return nil, err } @@ -67,18 +61,36 @@ func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionRe return m, nil } -// ServerReflectionService is the service API for ServerReflection service. -// Fields should be assigned to their respective handler implementations only before -// RegisterServerReflectionService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type ServerReflectionService struct { +// ServerReflectionServer is the server API for ServerReflection service. +// All implementations should embed UnimplementedServerReflectionServer +// for forward compatibility +type ServerReflectionServer interface { // The reflection service is structured as a bidirectional stream, ensuring // all related requests go to a single server. - ServerReflectionInfo func(ServerReflection_ServerReflectionInfoServer) error + ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error } -func (s *ServerReflectionService) serverReflectionInfo(_ interface{}, stream grpc.ServerStream) error { - return s.ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) +// UnimplementedServerReflectionServer should be embedded to have forward compatible implementations. +type UnimplementedServerReflectionServer struct { +} + +func (UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error { + return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") +} + +// UnsafeServerReflectionServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ServerReflectionServer will +// result in compilation errors. +type UnsafeServerReflectionServer interface { + mustEmbedUnimplementedServerReflectionServer() +} + +func RegisterServerReflectionServer(s *grpc.Server, srv ServerReflectionServer) { + s.RegisterService(&_ServerReflection_serviceDesc, srv) +} + +func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) } type ServerReflection_ServerReflectionInfoServer interface { @@ -103,54 +115,17 @@ func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRe return m, nil } -// RegisterServerReflectionService registers a service implementation with a gRPC server. -func RegisterServerReflectionService(s grpc.ServiceRegistrar, srv *ServerReflectionService) { - srvCopy := *srv - if srvCopy.ServerReflectionInfo == nil { - srvCopy.ServerReflectionInfo = func(ServerReflection_ServerReflectionInfoServer) error { - return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.reflection.v1alpha.ServerReflection", - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerReflectionInfo", - Handler: srvCopy.serverReflectionInfo, - ServerStreams: true, - ClientStreams: true, - }, +var _ServerReflection_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.reflection.v1alpha.ServerReflection", + HandlerType: (*ServerReflectionServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "ServerReflectionInfo", + Handler: _ServerReflection_ServerReflectionInfo_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "reflection/grpc_reflection_v1alpha/reflection.proto", - } - - s.RegisterService(&sd, nil) -} - -// ServerReflectionServer is the service API for ServerReflection service. -// New methods may be added to this interface if they are added to the service -// definition, which is not a backward-compatible change. For this reason, -// use of this type is not recommended unless you own the service definition. -type ServerReflectionServer interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error -} - -// UnimplementedServerReflectionServer can be embedded to have forward compatible implementations of -// ServerReflectionServer -type UnimplementedServerReflectionServer struct { -} - -func (UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error { - return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") -} - -// RegisterServerReflectionServer registers a service implementation with a gRPC server. -func RegisterServerReflectionServer(s grpc.ServiceRegistrar, srv ServerReflectionServer) { - str := &ServerReflectionService{ - ServerReflectionInfo: srv.ServerReflectionInfo, - } - RegisterServerReflectionService(s, str) + }, + Metadata: "reflection/grpc_reflection_v1alpha/reflection.proto", } diff --git a/reflection/grpc_testing/test_grpc.pb.go b/reflection/grpc_testing/test_grpc.pb.go index 503c8569368..095d10ae426 100644 --- a/reflection/grpc_testing/test_grpc.pb.go +++ b/reflection/grpc_testing/test_grpc.pb.go @@ -29,10 +29,6 @@ func NewSearchServiceClient(cc grpc.ClientConnInterface) SearchServiceClient { return &searchServiceClient{cc} } -var searchServiceSearchStreamDesc = &grpc.StreamDesc{ - StreamName: "Search", -} - func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) { out := new(SearchResponse) err := c.cc.Invoke(ctx, "/grpc.testing.SearchService/Search", in, out, opts...) @@ -42,14 +38,8 @@ func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opt return out, nil } -var searchServiceStreamingSearchStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingSearch", - ServerStreams: true, - ClientStreams: true, -} - func (c *searchServiceClient) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) { - stream, err := c.cc.NewStream(ctx, searchServiceStreamingSearchStreamDesc, "/grpc.testing.SearchService/StreamingSearch", opts...) + stream, err := c.cc.NewStream(ctx, &_SearchService_serviceDesc.Streams[0], "/grpc.testing.SearchService/StreamingSearch", opts...) if err != nil { return nil, err } @@ -79,34 +69,58 @@ func (x *searchServiceStreamingSearchClient) Recv() (*SearchResponse, error) { return m, nil } -// SearchServiceService is the service API for SearchService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterSearchServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type SearchServiceService struct { - Search func(context.Context, *SearchRequest) (*SearchResponse, error) - StreamingSearch func(SearchService_StreamingSearchServer) error +// SearchServiceServer is the server API for SearchService service. +// All implementations must embed UnimplementedSearchServiceServer +// for forward compatibility +type SearchServiceServer interface { + Search(context.Context, *SearchRequest) (*SearchResponse, error) + StreamingSearch(SearchService_StreamingSearchServer) error + mustEmbedUnimplementedSearchServiceServer() +} + +// UnimplementedSearchServiceServer must be embedded to have forward compatible implementations. +type UnimplementedSearchServiceServer struct { +} + +func (UnimplementedSearchServiceServer) Search(context.Context, *SearchRequest) (*SearchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Search not implemented") +} +func (UnimplementedSearchServiceServer) StreamingSearch(SearchService_StreamingSearchServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingSearch not implemented") +} +func (UnimplementedSearchServiceServer) mustEmbedUnimplementedSearchServiceServer() {} + +// UnsafeSearchServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SearchServiceServer will +// result in compilation errors. +type UnsafeSearchServiceServer interface { + mustEmbedUnimplementedSearchServiceServer() } -func (s *SearchServiceService) search(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func RegisterSearchServiceServer(s *grpc.Server, srv SearchServiceServer) { + s.RegisterService(&_SearchService_serviceDesc, srv) +} + +func _SearchService_Search_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SearchRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.Search(ctx, in) + return srv.(SearchServiceServer).Search(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.SearchService/Search", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.Search(ctx, req.(*SearchRequest)) + return srv.(SearchServiceServer).Search(ctx, req.(*SearchRequest)) } return interceptor(ctx, in, info, handler) } -func (s *SearchServiceService) streamingSearch(_ interface{}, stream grpc.ServerStream) error { - return s.StreamingSearch(&searchServiceStreamingSearchServer{stream}) + +func _SearchService_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(SearchServiceServer).StreamingSearch(&searchServiceStreamingSearchServer{stream}) } type SearchService_StreamingSearchServer interface { @@ -131,37 +145,22 @@ func (x *searchServiceStreamingSearchServer) Recv() (*SearchRequest, error) { return m, nil } -// RegisterSearchServiceService registers a service implementation with a gRPC server. -func RegisterSearchServiceService(s grpc.ServiceRegistrar, srv *SearchServiceService) { - srvCopy := *srv - if srvCopy.Search == nil { - srvCopy.Search = func(context.Context, *SearchRequest) (*SearchResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Search not implemented") - } - } - if srvCopy.StreamingSearch == nil { - srvCopy.StreamingSearch = func(SearchService_StreamingSearchServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingSearch not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.SearchService", - Methods: []grpc.MethodDesc{ - { - MethodName: "Search", - Handler: srvCopy.search, - }, +var _SearchService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.SearchService", + HandlerType: (*SearchServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Search", + Handler: _SearchService_Search_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingSearch", - Handler: srvCopy.streamingSearch, - ServerStreams: true, - ClientStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "StreamingSearch", + Handler: _SearchService_StreamingSearch_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "reflection/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + }, + Metadata: "reflection/grpc_testing/test.proto", } diff --git a/reflection/serverreflection_test.go b/reflection/serverreflection_test.go index 95b8269b4bd..55d1840fdc3 100644 --- a/reflection/serverreflection_test.go +++ b/reflection/serverreflection_test.go @@ -166,13 +166,8 @@ func (x) TestAllExtensionNumbersForType(t *testing.T) { // Do end2end tests. -type server struct{} - -func (s *server) Svc() *pb.SearchServiceService { - return &pb.SearchServiceService{ - Search: s.Search, - StreamingSearch: s.StreamingSearch, - } +type server struct { + pb.UnimplementedSearchServiceServer } func (s *server) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResponse, error) { @@ -200,7 +195,7 @@ func (x) TestReflectionEnd2end(t *testing.T) { t.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() - pb.RegisterSearchServiceService(s, (&server{}).Svc()) + pb.RegisterSearchServiceServer(s, &server{}) pbv3.RegisterSearchServiceV3Server(s, &serverV3{}) // Register reflection service on s. Register(s) diff --git a/regenerate.sh b/regenerate.sh index c10bc99a969..647a55afbbf 100755 --- a/regenerate.sh +++ b/regenerate.sh @@ -26,6 +26,11 @@ export GOBIN=${WORKDIR}/bin export PATH=${GOBIN}:${PATH} mkdir -p ${GOBIN} +echo "remove existing generated files" +# grpc_testingv3/testv3.pb.go is not re-generated because it was +# intentionally generated by an older version of protoc-gen-go. +rm -f $(find . -name '*.pb.go' | grep -v 'grpc_testingv3/testv3.pb.go') + echo "go install github.com/golang/protobuf/protoc-gen-go" (cd test/tools && go install github.com/golang/protobuf/protoc-gen-go) @@ -35,6 +40,7 @@ echo "go install cmd/protoc-gen-go-grpc" echo "git clone https://github.com/grpc/grpc-proto" git clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto +# Pull in code.proto as a proto dependency mkdir -p ${WORKDIR}/googleapis/google/rpc echo "curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto" curl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto @@ -59,21 +65,12 @@ curl --silent https://raw.githubusercontent.com/istio/istio/master/security/prot mkdir -p ${WORKDIR}/out -# Generates legacy gRPC Server symbols in addition to the newer Service symbols +# Generates sources without the embed requirement LEGACY_SOURCES=( - ${WORKDIR}/googleapis/google/rpc/code.proto ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto - ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto - ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto - ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto - ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto - ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto - ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto - ${WORKDIR}/grpc-proto/grpc/tls/provider/meshca/experimental/config.proto - ${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto profiling/proto/service.proto reflection/grpc_reflection_v1alpha/reflection.proto ) @@ -81,6 +78,14 @@ LEGACY_SOURCES=( # Generates only the new gRPC Service symbols SOURCES=( $(git ls-files --exclude-standard --cached --others "*.proto" | grep -v '^\(profiling/proto/service.proto\|reflection/grpc_reflection_v1alpha/reflection.proto\)$') + ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto + ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto + ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto + ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto + ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto + ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto + ${WORKDIR}/grpc-proto/grpc/tls/provider/meshca/experimental/config.proto + ${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto ) # These options of the form 'Mfoo.proto=bar' instruct the codegen to use an @@ -91,12 +96,20 @@ Menvoy/config/core/v3/config_source.proto=github.com/envoyproxy/go-control-plane for src in ${SOURCES[@]}; do echo "protoc ${src}" - protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out ${src} + protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out \ + -I"." \ + -I${WORKDIR}/grpc-proto \ + -I${WORKDIR}/googleapis \ + -I${WORKDIR}/data-plane-api \ + -I${WORKDIR}/udpa \ + -I${WORKDIR}/protoc-gen-validate \ + -I${WORKDIR}/istio \ + ${src} done for src in ${LEGACY_SOURCES[@]}; do echo "protoc ${src}" - protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},gen_unstable_server_interfaces=true:${WORKDIR}/out \ + protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},require_unimplemented_servers=false:${WORKDIR}/out \ -I"." \ -I${WORKDIR}/grpc-proto \ -I${WORKDIR}/googleapis \ diff --git a/security/advancedtls/advancedtls_integration_test.go b/security/advancedtls/advancedtls_integration_test.go index 3398644471e..a95fa56a6d6 100644 --- a/security/advancedtls/advancedtls_integration_test.go +++ b/security/advancedtls/advancedtls_integration_test.go @@ -130,8 +130,12 @@ func (cs *certStore) loadCerts() error { return nil } +type greeterServer struct { + pb.UnimplementedGreeterServer +} + // sayHello is a simple implementation of the pb.GreeterServer SayHello method. -func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { +func (greeterServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil } @@ -408,7 +412,7 @@ func (s) TestEnd2End(t *testing.T) { t.Fatalf("failed to listen: %v", err) } defer lis.Close() - pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) + pb.RegisterGreeterServer(s, greeterServer{}) go s.Serve(lis) clientOptions := &ClientOptions{ IdentityOptions: IdentityCertificateOptions{ diff --git a/stats/grpc_testing/test_grpc.pb.go b/stats/grpc_testing/test_grpc.pb.go index 32f93dde8db..89fe0aba5d6 100644 --- a/stats/grpc_testing/test_grpc.pb.go +++ b/stats/grpc_testing/test_grpc.pb.go @@ -38,10 +38,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient { return &testServiceClient{cc} } -var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnaryCall", -} - func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { out := new(SimpleResponse) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) @@ -51,14 +47,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op return out, nil } -var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{ - StreamName: "FullDuplexCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/FullDuplexCall", opts...) if err != nil { return nil, err } @@ -88,13 +78,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*SimpleResponse, error) { return m, nil } -var testServiceClientStreamCallStreamDesc = &grpc.StreamDesc{ - StreamName: "ClientStreamCall", - ClientStreams: true, -} - func (c *testServiceClient) ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceClientStreamCallStreamDesc, "/grpc.testing.TestService/ClientStreamCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/ClientStreamCall", opts...) if err != nil { return nil, err } @@ -127,13 +112,8 @@ func (x *testServiceClientStreamCallClient) CloseAndRecv() (*SimpleResponse, err return m, nil } -var testServiceServerStreamCallStreamDesc = &grpc.StreamDesc{ - StreamName: "ServerStreamCall", - ServerStreams: true, -} - func (c *testServiceClient) ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceServerStreamCallStreamDesc, "/grpc.testing.TestService/ServerStreamCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/ServerStreamCall", opts...) if err != nil { return nil, err } @@ -164,53 +144,73 @@ func (x *testServiceServerStreamCallClient) Recv() (*SimpleResponse, error) { return m, nil } -// TestServiceService is the service API for TestService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterTestServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type TestServiceService struct { +// TestServiceServer is the server API for TestService service. +// All implementations must embed UnimplementedTestServiceServer +// for forward compatibility +type TestServiceServer interface { // One request followed by one response. // The server returns the client id as-is. - UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) + UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) // A sequence of requests with each request served by the server immediately. // As one request could lead to multiple responses, this interface // demonstrates the idea of full duplexing. - FullDuplexCall func(TestService_FullDuplexCallServer) error + FullDuplexCall(TestService_FullDuplexCallServer) error // Client stream - ClientStreamCall func(TestService_ClientStreamCallServer) error + ClientStreamCall(TestService_ClientStreamCallServer) error // Server stream - ServerStreamCall func(*SimpleRequest, TestService_ServerStreamCallServer) error + ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error + mustEmbedUnimplementedTestServiceServer() } -func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +// UnimplementedTestServiceServer must be embedded to have forward compatible implementations. +type UnimplementedTestServiceServer struct { +} + +func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") +} +func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error { + return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") +} +func (UnimplementedTestServiceServer) ClientStreamCall(TestService_ClientStreamCallServer) error { + return status.Errorf(codes.Unimplemented, "method ClientStreamCall not implemented") +} +func (UnimplementedTestServiceServer) ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error { + return status.Errorf(codes.Unimplemented, "method ServerStreamCall not implemented") +} +func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {} + +// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to TestServiceServer will +// result in compilation errors. +type UnsafeTestServiceServer interface { + mustEmbedUnimplementedTestServiceServer() +} + +func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { + s.RegisterService(&_TestService_serviceDesc, srv) +} + +func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnaryCall(ctx, in) + return srv.(TestServiceServer).UnaryCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.TestService/UnaryCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnaryCall(ctx, req.(*SimpleRequest)) + return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) } return interceptor(ctx, in, info, handler) } -func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error { - return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} -func (s *TestServiceService) clientStreamCall(_ interface{}, stream grpc.ServerStream) error { - return s.ClientStreamCall(&testServiceClientStreamCallServer{stream}) -} -func (s *TestServiceService) serverStreamCall(_ interface{}, stream grpc.ServerStream) error { - m := new(SimpleRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return s.ServerStreamCall(m, &testServiceServerStreamCallServer{stream}) + +func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) } type TestService_FullDuplexCallServer interface { @@ -235,6 +235,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*SimpleRequest, error) { return m, nil } +func _TestService_ClientStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).ClientStreamCall(&testServiceClientStreamCallServer{stream}) +} + type TestService_ClientStreamCallServer interface { SendAndClose(*SimpleResponse) error Recv() (*SimpleRequest, error) @@ -257,6 +261,14 @@ func (x *testServiceClientStreamCallServer) Recv() (*SimpleRequest, error) { return m, nil } +func _TestService_ServerStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(SimpleRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(TestServiceServer).ServerStreamCall(m, &testServiceServerStreamCallServer{stream}) +} + type TestService_ServerStreamCallServer interface { Send(*SimpleResponse) error grpc.ServerStream @@ -270,57 +282,32 @@ func (x *testServiceServerStreamCallServer) Send(m *SimpleResponse) error { return x.ServerStream.SendMsg(m) } -// RegisterTestServiceService registers a service implementation with a gRPC server. -func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { - srvCopy := *srv - if srvCopy.UnaryCall == nil { - srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") - } - } - if srvCopy.FullDuplexCall == nil { - srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error { - return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") - } - } - if srvCopy.ClientStreamCall == nil { - srvCopy.ClientStreamCall = func(TestService_ClientStreamCallServer) error { - return status.Errorf(codes.Unimplemented, "method ClientStreamCall not implemented") - } - } - if srvCopy.ServerStreamCall == nil { - srvCopy.ServerStreamCall = func(*SimpleRequest, TestService_ServerStreamCallServer) error { - return status.Errorf(codes.Unimplemented, "method ServerStreamCall not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: srvCopy.unaryCall, - }, +var _TestService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.TestService", + HandlerType: (*TestServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UnaryCall", + Handler: _TestService_UnaryCall_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "FullDuplexCall", - Handler: srvCopy.fullDuplexCall, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "ClientStreamCall", - Handler: srvCopy.clientStreamCall, - ClientStreams: true, - }, - { - StreamName: "ServerStreamCall", - Handler: srvCopy.serverStreamCall, - ServerStreams: true, - }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "FullDuplexCall", + Handler: _TestService_FullDuplexCall_Handler, + ServerStreams: true, + ClientStreams: true, }, - Metadata: "stats/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + { + StreamName: "ClientStreamCall", + Handler: _TestService_ClientStreamCall_Handler, + ClientStreams: true, + }, + { + StreamName: "ServerStreamCall", + Handler: _TestService_ServerStreamCall_Handler, + ServerStreams: true, + }, + }, + Metadata: "stats/grpc_testing/test.proto", } diff --git a/stats/stats_test.go b/stats/stats_test.go index 90b9cdbee9c..d047d48bc5e 100644 --- a/stats/stats_test.go +++ b/stats/stats_test.go @@ -73,15 +73,8 @@ var ( errorID int32 = 32202 ) -type testServer struct{} - -func (s *testServer) Svc() *testpb.TestServiceService { - return &testpb.TestServiceService{ - UnaryCall: s.UnaryCall, - FullDuplexCall: s.FullDuplexCall, - ClientStreamCall: s.ClientStreamCall, - ServerStreamCall: s.ServerStreamCall, - } +type testServer struct { + testpb.UnimplementedTestServiceServer } func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { @@ -172,7 +165,7 @@ type test struct { clientStatsHandler stats.Handler serverStatsHandler stats.Handler - testService *testpb.TestServiceService // nil means none + testServer testpb.TestServiceServer // nil means none // srv and srvAddr are set once startServer is called. srv *grpc.Server srvAddr string @@ -207,8 +200,8 @@ func newTest(t *testing.T, tc *testConfig, ch stats.Handler, sh stats.Handler) * // startServer starts a gRPC server listening. Callers should defer a // call to te.tearDown to clean up. -func (te *test) startServer(ts *testpb.TestServiceService) { - te.testService = ts +func (te *test) startServer(ts testpb.TestServiceServer) { + te.testServer = ts lis, err := net.Listen("tcp", "localhost:0") if err != nil { te.t.Fatalf("Failed to listen: %v", err) @@ -225,8 +218,8 @@ func (te *test) startServer(ts *testpb.TestServiceService) { } s := grpc.NewServer(opts...) te.srv = s - if te.testService != nil { - testpb.RegisterTestServiceService(s, te.testService) + if te.testServer != nil { + testpb.RegisterTestServiceServer(s, te.testServer) } go s.Serve(lis) @@ -822,7 +815,7 @@ func checkServerStats(t *testing.T, got []*gotData, expect *expectedData, checkF func testServerStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { h := &statshandler{} te := newTest(t, tc, nil, h) - te.startServer((&testServer{}).Svc()) + te.startServer(&testServer{}) defer te.tearDown() var ( @@ -1113,7 +1106,7 @@ func checkClientStats(t *testing.T, got []*gotData, expect *expectedData, checkF func testClientStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs map[int]*checkFuncWithCount) { h := &statshandler{} te := newTest(t, tc, h, nil) - te.startServer((&testServer{}).Svc()) + te.startServer(&testServer{}) defer te.tearDown() var ( diff --git a/stress/client/main.go b/stress/client/main.go index c91aeb0a418..c5bfffa4e51 100644 --- a/stress/client/main.go +++ b/stress/client/main.go @@ -146,6 +146,7 @@ func (g *gauge) get() int64 { // server implements metrics server functions. type server struct { + metricspb.UnimplementedMetricsServiceServer mutex sync.RWMutex // gauges is a map from /stress_test/server_/channel_/stub_/qps to its qps gauge. gauges map[string]*gauge @@ -156,13 +157,6 @@ func newMetricsServer() *server { return &server{gauges: make(map[string]*gauge)} } -func (s *server) Svc() *metricspb.MetricsServiceService { - return &metricspb.MetricsServiceService{ - GetAllGauges: s.GetAllGauges, - GetGauge: s.GetGauge, - } -} - // GetAllGauges returns all gauges. func (s *server) GetAllGauges(in *metricspb.EmptyMessage, stream metricspb.MetricsService_GetAllGaugesServer) error { s.mutex.RLock() @@ -208,8 +202,9 @@ func startServer(server *server, port int) { } s := grpc.NewServer() - metricspb.RegisterMetricsServiceService(s, server.Svc()) + metricspb.RegisterMetricsServiceServer(s, server) s.Serve(lis) + } // performRPCs uses weightedRandomTestSelector to select test case and runs the tests. diff --git a/stress/grpc_testing/metrics_grpc.pb.go b/stress/grpc_testing/metrics_grpc.pb.go index b28a52e79f7..07d480b0b6a 100644 --- a/stress/grpc_testing/metrics_grpc.pb.go +++ b/stress/grpc_testing/metrics_grpc.pb.go @@ -32,13 +32,8 @@ func NewMetricsServiceClient(cc grpc.ClientConnInterface) MetricsServiceClient { return &metricsServiceClient{cc} } -var metricsServiceGetAllGaugesStreamDesc = &grpc.StreamDesc{ - StreamName: "GetAllGauges", - ServerStreams: true, -} - func (c *metricsServiceClient) GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) { - stream, err := c.cc.NewStream(ctx, metricsServiceGetAllGaugesStreamDesc, "/grpc.testing.MetricsService/GetAllGauges", opts...) + stream, err := c.cc.NewStream(ctx, &_MetricsService_serviceDesc.Streams[0], "/grpc.testing.MetricsService/GetAllGauges", opts...) if err != nil { return nil, err } @@ -69,10 +64,6 @@ func (x *metricsServiceGetAllGaugesClient) Recv() (*GaugeResponse, error) { return m, nil } -var metricsServiceGetGaugeStreamDesc = &grpc.StreamDesc{ - StreamName: "GetGauge", -} - func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) { out := new(GaugeResponse) err := c.cc.Invoke(ctx, "/grpc.testing.MetricsService/GetGauge", in, out, opts...) @@ -82,41 +73,47 @@ func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, o return out, nil } -// MetricsServiceService is the service API for MetricsService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterMetricsServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type MetricsServiceService struct { +// MetricsServiceServer is the server API for MetricsService service. +// All implementations must embed UnimplementedMetricsServiceServer +// for forward compatibility +type MetricsServiceServer interface { // Returns the values of all the gauges that are currently being maintained by // the service - GetAllGauges func(*EmptyMessage, MetricsService_GetAllGaugesServer) error + GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error // Returns the value of one gauge - GetGauge func(context.Context, *GaugeRequest) (*GaugeResponse, error) + GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error) + mustEmbedUnimplementedMetricsServiceServer() +} + +// UnimplementedMetricsServiceServer must be embedded to have forward compatible implementations. +type UnimplementedMetricsServiceServer struct { +} + +func (UnimplementedMetricsServiceServer) GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error { + return status.Errorf(codes.Unimplemented, "method GetAllGauges not implemented") +} +func (UnimplementedMetricsServiceServer) GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetGauge not implemented") +} +func (UnimplementedMetricsServiceServer) mustEmbedUnimplementedMetricsServiceServer() {} + +// UnsafeMetricsServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to MetricsServiceServer will +// result in compilation errors. +type UnsafeMetricsServiceServer interface { + mustEmbedUnimplementedMetricsServiceServer() +} + +func RegisterMetricsServiceServer(s *grpc.Server, srv MetricsServiceServer) { + s.RegisterService(&_MetricsService_serviceDesc, srv) } -func (s *MetricsServiceService) getAllGauges(_ interface{}, stream grpc.ServerStream) error { +func _MetricsService_GetAllGauges_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(EmptyMessage) if err := stream.RecvMsg(m); err != nil { return err } - return s.GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream}) -} -func (s *MetricsServiceService) getGauge(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GaugeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return s.GetGauge(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: s, - FullMethod: "/grpc.testing.MetricsService/GetGauge", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.GetGauge(ctx, req.(*GaugeRequest)) - } - return interceptor(ctx, in, info, handler) + return srv.(MetricsServiceServer).GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream}) } type MetricsService_GetAllGaugesServer interface { @@ -132,36 +129,39 @@ func (x *metricsServiceGetAllGaugesServer) Send(m *GaugeResponse) error { return x.ServerStream.SendMsg(m) } -// RegisterMetricsServiceService registers a service implementation with a gRPC server. -func RegisterMetricsServiceService(s grpc.ServiceRegistrar, srv *MetricsServiceService) { - srvCopy := *srv - if srvCopy.GetAllGauges == nil { - srvCopy.GetAllGauges = func(*EmptyMessage, MetricsService_GetAllGaugesServer) error { - return status.Errorf(codes.Unimplemented, "method GetAllGauges not implemented") - } +func _MetricsService_GetGauge_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GaugeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MetricsServiceServer).GetGauge(ctx, in) } - if srvCopy.GetGauge == nil { - srvCopy.GetGauge = func(context.Context, *GaugeRequest) (*GaugeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetGauge not implemented") - } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.testing.MetricsService/GetGauge", } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.MetricsService", - Methods: []grpc.MethodDesc{ - { - MethodName: "GetGauge", - Handler: srvCopy.getGauge, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "GetAllGauges", - Handler: srvCopy.getAllGauges, - ServerStreams: true, - }, - }, - Metadata: "stress/grpc_testing/metrics.proto", + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MetricsServiceServer).GetGauge(ctx, req.(*GaugeRequest)) } + return interceptor(ctx, in, info, handler) +} - s.RegisterService(&sd, nil) +var _MetricsService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.MetricsService", + HandlerType: (*MetricsServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetGauge", + Handler: _MetricsService_GetGauge_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "GetAllGauges", + Handler: _MetricsService_GetAllGauges_Handler, + ServerStreams: true, + }, + }, + Metadata: "stress/grpc_testing/metrics.proto", } diff --git a/test/balancer_test.go b/test/balancer_test.go index 43e50210349..f0189cf2644 100644 --- a/test/balancer_test.go +++ b/test/balancer_test.go @@ -150,7 +150,7 @@ func (s) TestCredsBundleFromBalancer(t *testing.T) { te.customServerOptions = []grpc.ServerOption{ grpc.Creds(creds), } - te.startServer((&testServer{}).Svc()) + te.startServer(&testServer{}) defer te.tearDown() cc := te.clientConn() @@ -179,7 +179,7 @@ func testPickExtraMetadata(t *testing.T, e env) { grpc.WithBalancerName(testBalancerName), grpc.WithUserAgent(testUserAgent), } - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() // Set resolver to xds to trigger the extra metadata code path. @@ -228,7 +228,7 @@ func testDoneInfo(t *testing.T, e env) { grpc.WithBalancerName(testBalancerName), } te.userAgent = failAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -498,7 +498,7 @@ func (s) TestAddressAttributesInNewSubConn(t *testing.T) { } s := grpc.NewServer() - testpb.RegisterTestServiceService(s, (&testServer{}).Svc()) + testpb.RegisterTestServiceServer(s, &testServer{}) go s.Serve(lis) defer s.Stop() t.Logf("Started gRPC server at %s...", lis.Addr().String()) @@ -556,12 +556,12 @@ func (s) TestServersSwap(t *testing.T) { t.Fatalf("Error while listening. Err: %v", err) } s := grpc.NewServer() - ts := &testpb.TestServiceService{ - UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{ + unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { return &testpb.SimpleResponse{Username: username}, nil }, } - testpb.RegisterTestServiceService(s, ts) + testpb.RegisterTestServiceServer(s, ts) go s.Serve(lis) return lis.Addr().String(), s.Stop } @@ -616,12 +616,12 @@ func (s) TestEmptyAddrs(t *testing.T) { s := grpc.NewServer() defer s.Stop() const one = "1" - ts := &testpb.TestServiceService{ - UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{ + unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { return &testpb.SimpleResponse{Username: one}, nil }, } - testpb.RegisterTestServiceService(s, ts) + testpb.RegisterTestServiceServer(s, ts) go s.Serve(lis) // Initialize pickfirst client @@ -705,12 +705,12 @@ func (s) TestWaitForReady(t *testing.T) { s := grpc.NewServer() defer s.Stop() const one = "1" - ts := &testpb.TestServiceService{ - UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{ + unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { return &testpb.SimpleResponse{Username: one}, nil }, } - testpb.RegisterTestServiceService(s, ts) + testpb.RegisterTestServiceServer(s, ts) go s.Serve(lis) // Initialize client diff --git a/test/channelz_linux_go110_test.go b/test/channelz_linux_go110_test.go index 35fd2e82680..dea374bfc08 100644 --- a/test/channelz_linux_go110_test.go +++ b/test/channelz_linux_go110_test.go @@ -43,7 +43,7 @@ func testCZSocketMetricsSocketOption(t *testing.T, e env) { czCleanup := channelz.NewChannelzStorage() defer czCleanupWrapper(czCleanup, t) te := newTest(t, e) - te.startServer((&testServer{security: e.security}).Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := testpb.NewTestServiceClient(cc) diff --git a/test/channelz_test.go b/test/channelz_test.go index 1f2197849e6..9f8af01e7c7 100644 --- a/test/channelz_test.go +++ b/test/channelz_test.go @@ -85,7 +85,7 @@ func (s) TestCZServerRegistrationAndDeletion(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServers(testServer{security: e.security}.Svc(), c.total) + te.startServers(&testServer{security: e.security}, c.total) ss, end := channelz.GetServers(c.start, c.max) if int64(len(ss)) != c.length || end != c.end { @@ -104,7 +104,7 @@ func (s) TestCZGetServer(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() ss, _ := channelz.GetServers(0, 0) @@ -253,7 +253,7 @@ func (s) TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) { num := 3 // number of backends te := newTest(t, e) var svrAddrs []resolver.Address - te.startServers(testServer{security: e.security}.Svc(), num) + te.startServers(&testServer{security: e.security}, num) r := manual.NewBuilderWithScheme("whatever") for _, a := range te.srvAddrs { svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) @@ -339,7 +339,7 @@ func (s) TestCZServerSocketRegistrationAndDeletion(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) var ccs []*grpc.ClientConn for i := 0; i < c.total; i++ { cc := te.clientConn() @@ -504,7 +504,7 @@ func (s) TestCZChannelMetrics(t *testing.T) { te := newTest(t, e) te.maxClientSendMsgSize = newInt(8) var svrAddrs []resolver.Address - te.startServers(testServer{security: e.security}.Svc(), num) + te.startServers(&testServer{security: e.security}, num) r := manual.NewBuilderWithScheme("whatever") for _, a := range te.srvAddrs { svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) @@ -590,7 +590,7 @@ func (s) TestCZServerMetrics(t *testing.T) { e := tcpClearRREnv te := newTest(t, e) te.maxServerReceiveMsgSize = newInt(8) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := testpb.NewTestServiceClient(cc) @@ -861,7 +861,7 @@ func (s) TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) { te := newTest(t, e) te.maxServerReceiveMsgSize = newInt(20) te.maxClientReceiveMsgSize = newInt(20) - rcw := te.startServerWithConnControl(testServer{security: e.security}.Svc()) + rcw := te.startServerWithConnControl(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} @@ -963,7 +963,7 @@ func (s) TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *t // Avoid overflowing connection level flow control window, which will lead to // transport being closed. te.serverInitialConnWindowSize = 65536 * 2 - ts := &testpb.TestServiceService{FullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { + ts := &stubServer{fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { stream.Send(&testpb.StreamingOutputCallResponse{}) <-stream.Context().Done() return status.Errorf(codes.DeadlineExceeded, "deadline exceeded or cancelled") @@ -1048,7 +1048,7 @@ func (s) TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) { te.serverInitialConnWindowSize = 65536 te.clientInitialWindowSize = 65536 te.clientInitialConnWindowSize = 65536 - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := testpb.NewTestServiceClient(cc) @@ -1169,7 +1169,7 @@ func (s) TestCZClientSocketMetricsKeepAlive(t *testing.T) { MinTime: 500 * time.Millisecond, PermitWithoutStream: true, })) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) te.clientConn() // Dial the server defer te.tearDown() if err := verifyResultWithDelay(func() (bool, error) { @@ -1211,7 +1211,7 @@ func (s) TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) { te := newTest(t, e) te.maxServerReceiveMsgSize = newInt(20) te.maxClientReceiveMsgSize = newInt(20) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc, _ := te.clientConnWithConnControl() tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} @@ -1282,7 +1282,7 @@ func (s) TestCZServerSocketMetricsKeepAlive(t *testing.T) { Timeout: 100 * time.Millisecond, }) te.customServerOptions = append(te.customServerOptions, kpOption) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := testpb.NewTestServiceClient(cc) @@ -1342,7 +1342,7 @@ func (s) TestCZSocketGetSecurityValueTLS(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpTLSRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() te.clientConn() if err := verifyResultWithDelay(func() (bool, error) { @@ -1467,7 +1467,7 @@ func (s) TestCZSubChannelTraceCreationDeletion(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) te.resolverScheme = r.Scheme() @@ -1560,7 +1560,7 @@ func (s) TestCZChannelAddressResolutionChange(t *testing.T) { e := tcpClearRREnv e.balancer = "" te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") addrs := []resolver.Address{{Addr: te.srvAddr}} r.InitialState(resolver.State{Addresses: addrs}) @@ -1663,7 +1663,7 @@ func (s) TestCZSubChannelPickedNewAddress(t *testing.T) { e := tcpClearRREnv e.balancer = "" te := newTest(t, e) - te.startServers(testServer{security: e.security}.Svc(), 3) + te.startServers(&testServer{security: e.security}, 3) r := manual.NewBuilderWithScheme("whatever") var svrAddrs []resolver.Address for _, a := range te.srvAddrs { @@ -1722,7 +1722,7 @@ func (s) TestCZSubChannelConnectivityState(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) te.resolverScheme = r.Scheme() @@ -1816,7 +1816,7 @@ func (s) TestCZChannelConnectivityState(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) te.resolverScheme = r.Scheme() @@ -1939,7 +1939,7 @@ func (s) TestCZTraceOverwriteSubChannelDeletion(t *testing.T) { te := newTest(t, e) channelz.SetMaxTraceEntry(1) defer channelz.ResetMaxTraceEntryToDefault() - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) te.resolverScheme = r.Scheme() @@ -1997,7 +1997,7 @@ func (s) TestCZTraceTopChannelDeletionTraceClear(t *testing.T) { defer czCleanupWrapper(czCleanup, t) e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) r := manual.NewBuilderWithScheme("whatever") r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) te.resolverScheme = r.Scheme() diff --git a/test/creds_test.go b/test/creds_test.go index a4d1e6cda0c..46bdd30dc85 100644 --- a/test/creds_test.go +++ b/test/creds_test.go @@ -87,7 +87,7 @@ func (s) TestCredsBundleBoth(t *testing.T) { te.customServerOptions = []grpc.ServerOption{ grpc.Creds(creds), } - te.startServer(testServer{}.Svc()) + te.startServer(&testServer{}) defer te.tearDown() cc := te.clientConn() @@ -109,7 +109,7 @@ func (s) TestCredsBundleTransportCredentials(t *testing.T) { te.customServerOptions = []grpc.ServerOption{ grpc.Creds(creds), } - te.startServer(testServer{}.Svc()) + te.startServer(&testServer{}) defer te.tearDown() cc := te.clientConn() @@ -125,7 +125,7 @@ func (s) TestCredsBundlePerRPCCredentials(t *testing.T) { te.customDialOptions = []grpc.DialOption{ grpc.WithCredentialsBundle(&testCredsBundle{t: t, mode: bundlePerRPCOnly}), } - te.startServer(testServer{}.Svc()) + te.startServer(&testServer{}) defer te.tearDown() cc := te.clientConn() @@ -159,7 +159,7 @@ func (c *clientTimeoutCreds) Clone() credentials.TransportCredentials { func (s) TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) { te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "empty"}) te.userAgent = testAppUA - te.startServer(testServer{security: te.e.security}.Svc()) + te.startServer(&testServer{security: te.e.security}) defer te.tearDown() cc := te.clientConn(grpc.WithTransportCredentials(&clientTimeoutCreds{})) @@ -183,7 +183,7 @@ func (s) TestGRPCMethodAccessibleToCredsViaContextRequestInfo(t *testing.T) { const wantMethod = "/grpc.testing.TestService/EmptyCall" te := newTest(t, env{name: "context-request-info", network: "tcp"}) te.userAgent = testAppUA - te.startServer(testServer{security: te.e.security}.Svc()) + te.startServer(&testServer{security: te.e.security}) defer te.tearDown() cc := te.clientConn(grpc.WithPerRPCCredentials(&methodTestCreds{})) @@ -218,7 +218,7 @@ func (c clientAlwaysFailCred) Clone() credentials.TransportCredentials { func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) { te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"}) - te.startServer(testServer{security: te.e.security}.Svc()) + te.startServer(&testServer{security: te.e.security}) defer te.tearDown() opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})} @@ -246,7 +246,7 @@ func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) { func (s) TestWaitForReadyRPCErrorOnBadCertificates(t *testing.T) { te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"}) - te.startServer(testServer{security: te.e.security}.Svc()) + te.startServer(&testServer{security: te.e.security}) defer te.tearDown() opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})} @@ -312,7 +312,7 @@ func testPerRPCCredentialsViaDialOptions(t *testing.T, e env) { te := newTest(t, e) te.tapHandle = authHandle te.perRPCCreds = testPerRPCCredentials{} - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -331,7 +331,7 @@ func (s) TestPerRPCCredentialsViaCallOptions(t *testing.T) { func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) { te := newTest(t, e) te.tapHandle = authHandle - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -371,7 +371,7 @@ func testPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T, e env) { } return ctx, nil } - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() diff --git a/test/end2end_test.go b/test/end2end_test.go index 01f99cb2997..0842dccaad0 100644 --- a/test/end2end_test.go +++ b/test/end2end_test.go @@ -126,6 +126,8 @@ var ( var raceMode bool // set by race.go in race mode type testServer struct { + testpb.UnimplementedTestServiceServer + security string // indicate the authentication protocol used by this server. earlyFail bool // whether to error out the execution of a service handler prematurely. setAndSendHeader bool // whether to call setHeader and sendHeader. @@ -134,20 +136,6 @@ type testServer struct { unaryCallSleepTime time.Duration } -// Svc returns a registerable TestService for this testServer instances. -// Because `s` is passed by value for convenience, any subsequent changes to -// `s` are not recognized. -func (s testServer) Svc() *testpb.TestServiceService { - return &testpb.TestServiceService{ - EmptyCall: s.EmptyCall, - UnaryCall: s.UnaryCall, - StreamingOutputCall: s.StreamingOutputCall, - StreamingInputCall: s.StreamingInputCall, - FullDuplexCall: s.FullDuplexCall, - HalfDuplexCall: s.HalfDuplexCall, - } -} - func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { if md, ok := metadata.FromIncomingContext(ctx); ok { // For testing purpose, returns an error if user-agent is failAppUA. @@ -578,7 +566,7 @@ func newTest(t *testing.T, e env) *test { return te } -func (te *test) listenAndServe(ts *testpb.TestServiceService, listen func(network, address string) (net.Listener, error)) net.Listener { +func (te *test) listenAndServe(ts testpb.TestServiceServer, listen func(network, address string) (net.Listener, error)) net.Listener { te.t.Helper() te.t.Logf("Running test in %s environment...", te.e.name) sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(te.maxStream)} @@ -638,7 +626,7 @@ func (te *test) listenAndServe(ts *testpb.TestServiceService, listen func(networ sopts = append(sopts, te.customServerOptions...) s := grpc.NewServer(sopts...) if ts != nil { - testpb.RegisterTestServiceService(s, ts) + testpb.RegisterTestServiceServer(s, ts) } // Create a new default health server if enableHealthServer is set, or use @@ -703,20 +691,20 @@ func (w wrapHS) Stop() { w.s.Close() } -func (te *test) startServerWithConnControl(ts *testpb.TestServiceService) *listenerWrapper { +func (te *test) startServerWithConnControl(ts testpb.TestServiceServer) *listenerWrapper { l := te.listenAndServe(ts, listenWithConnControl) return l.(*listenerWrapper) } // startServer starts a gRPC server exposing the provided TestService // implementation. Callers should defer a call to te.tearDown to clean up -func (te *test) startServer(ts *testpb.TestServiceService) { +func (te *test) startServer(ts testpb.TestServiceServer) { te.t.Helper() te.listenAndServe(ts, net.Listen) } // startServers starts 'num' gRPC servers exposing the provided TestService. -func (te *test) startServers(ts *testpb.TestServiceService, num int) { +func (te *test) startServers(ts testpb.TestServiceServer, num int) { for i := 0; i < num; i++ { te.startServer(ts) te.srvs = append(te.srvs, te.srv.(*grpc.Server)) @@ -924,7 +912,7 @@ func (s) TestContextDeadlineNotIgnored(t *testing.T) { } te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -958,7 +946,7 @@ func testTimeoutOnDeadServer(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1000,7 +988,7 @@ func (s) TestServerGracefulStopIdempotent(t *testing.T) { func testServerGracefulStopIdempotent(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() for i := 0; i < 3; i++ { @@ -1020,7 +1008,7 @@ func (s) TestServerGoAway(t *testing.T) { func testServerGoAway(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1072,7 +1060,7 @@ func testServerGoAwayPendingRPC(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1146,7 +1134,7 @@ func testServerMultipleGoAwayPendingRPC(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1233,7 +1221,7 @@ func testConcurrentClientConnCloseAndServerGoAway(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1270,7 +1258,7 @@ func testConcurrentServerStopAndGoAway(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1345,7 +1333,7 @@ func (s) TestClientConnCloseAfterGoAwayWithActiveStream(t *testing.T) { func testClientConnCloseAfterGoAwayWithActiveStream(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() tc := testpb.NewTestServiceClient(cc) @@ -1384,7 +1372,7 @@ func testFailFast(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -1743,7 +1731,7 @@ func (s) TestServiceConfigMaxMsgSize(t *testing.T) { te1.resolverScheme = r.Scheme() te1.nonBlockingDial = true - te1.startServer(testServer{security: e.security}.Svc()) + te1.startServer(&testServer{security: e.security}) cc1 := te1.clientConn(grpc.WithResolvers(r)) addrs := []resolver.Address{{Addr: te1.srvAddr}} @@ -1833,7 +1821,7 @@ func (s) TestServiceConfigMaxMsgSize(t *testing.T) { te2.maxClientReceiveMsgSize = newInt(1024) te2.maxClientSendMsgSize = newInt(1024) - te2.startServer(testServer{security: e.security}.Svc()) + te2.startServer(&testServer{security: e.security}) defer te2.tearDown() cc2 := te2.clientConn(grpc.WithResolvers(r)) r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: te2.srvAddr}}, ServiceConfig: sc}) @@ -1893,7 +1881,7 @@ func (s) TestServiceConfigMaxMsgSize(t *testing.T) { te3.maxClientReceiveMsgSize = newInt(4096) te3.maxClientSendMsgSize = newInt(4096) - te3.startServer(testServer{security: e.security}.Svc()) + te3.startServer(&testServer{security: e.security}) defer te3.tearDown() cc3 := te3.clientConn(grpc.WithResolvers(r)) @@ -1977,7 +1965,7 @@ func (s) TestServiceConfigMaxMsgSize(t *testing.T) { // test makes sure read from streaming RPC doesn't fail in this case. func (s) TestStreamingRPCWithTimeoutInServiceConfigRecv(t *testing.T) { te := testServiceConfigSetup(t, tcpClearRREnv) - te.startServer(testServer{security: tcpClearRREnv.security}.Svc()) + te.startServer(&testServer{security: tcpClearRREnv.security}) defer te.tearDown() r := manual.NewBuilderWithScheme("whatever") @@ -2059,7 +2047,7 @@ func testPreloaderClientSend(t *testing.T, e env) { "grpc: addrConn.resetTransport failed to create client transport: connection error", "Failed to dial : context canceled; please retry.", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2133,7 +2121,7 @@ func testMaxMsgSizeClientDefault(t *testing.T, e env) { "grpc: addrConn.resetTransport failed to create client transport: connection error", "Failed to dial : context canceled; please retry.", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2197,7 +2185,7 @@ func testMaxMsgSizeClientAPI(t *testing.T, e env) { "grpc: addrConn.resetTransport failed to create client transport: connection error", "Failed to dial : context canceled; please retry.", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2282,7 +2270,7 @@ func testMaxMsgSizeServerAPI(t *testing.T, e env) { "grpc: addrConn.resetTransport failed to create client transport: connection error", "Failed to dial : context canceled; please retry.", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2387,7 +2375,7 @@ func testTap(t *testing.T, e env) { "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", "grpc: addrConn.resetTransport failed to create client transport: connection error", ) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -2482,7 +2470,7 @@ func (s) TestHealthCheckSuccess(t *testing.T) { func testHealthCheckSuccess(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) te.setHealthServingStatus(defaultHealthService, healthpb.HealthCheckResponse_SERVING) defer te.tearDown() @@ -2504,7 +2492,7 @@ func testHealthCheckFailure(t *testing.T, e env) { "grpc: the client connection is closing; please retry", ) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) te.setHealthServingStatus(defaultHealthService, healthpb.HealthCheckResponse_SERVING) defer te.tearDown() @@ -2528,7 +2516,7 @@ func (s) TestHealthCheckOff(t *testing.T) { func testHealthCheckOff(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() verifyHealthCheckErrCode(t, 1*time.Second, te.clientConn(), defaultHealthService, codes.NotFound) @@ -2545,7 +2533,7 @@ func (s) TestHealthWatchMultipleClients(t *testing.T) { func testHealthWatchMultipleClients(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -2574,7 +2562,7 @@ func (s) TestHealthWatchSameStatus(t *testing.T) { func testHealthWatchSameStatus(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() stream, cf := newHealthCheckStream(t, te.clientConn(), defaultHealthService) @@ -2602,7 +2590,7 @@ func testHealthWatchSetServiceStatusBeforeStartingServer(t *testing.T, e env) { te := newTest(t, e) te.healthServer = hs hs.SetServingStatus(defaultHealthService, healthpb.HealthCheckResponse_SERVING) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() stream, cf := newHealthCheckStream(t, te.clientConn(), defaultHealthService) @@ -2623,7 +2611,7 @@ func (s) TestHealthWatchDefaultStatusChange(t *testing.T) { func testHealthWatchDefaultStatusChange(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() stream, cf := newHealthCheckStream(t, te.clientConn(), defaultHealthService) @@ -2644,7 +2632,7 @@ func (s) TestHealthWatchSetServiceStatusBeforeClientCallsWatch(t *testing.T) { func testHealthWatchSetServiceStatusBeforeClientCallsWatch(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) te.setHealthServingStatus(defaultHealthService, healthpb.HealthCheckResponse_SERVING) defer te.tearDown() @@ -2664,7 +2652,7 @@ func (s) TestHealthWatchOverallServerHealthChange(t *testing.T) { func testHealthWatchOverallServerHealthChange(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() stream, cf := newHealthCheckStream(t, te.clientConn(), "") @@ -2696,7 +2684,7 @@ func (s) TestUnknownHandler(t *testing.T) { func testUnknownHandler(t *testing.T, e env, unknownHandler grpc.StreamHandler) { te := newTest(t, e) te.unknownHandler = unknownHandler - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() verifyHealthCheckErrCode(t, 1*time.Second, te.clientConn(), "", codes.Unauthenticated) } @@ -2712,7 +2700,7 @@ func (s) TestHealthCheckServingStatus(t *testing.T) { func testHealthCheckServingStatus(t *testing.T, e env) { te := newTest(t, e) te.enableHealthServer = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -2733,7 +2721,7 @@ func (s) TestEmptyUnaryWithUserAgent(t *testing.T) { func testEmptyUnaryWithUserAgent(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -2764,7 +2752,7 @@ func (s) TestFailedEmptyUnary(t *testing.T) { func testFailedEmptyUnary(t *testing.T, e env) { te := newTest(t, e) te.userAgent = failAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2783,7 +2771,7 @@ func (s) TestLargeUnary(t *testing.T) { func testLargeUnary(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2822,7 +2810,7 @@ func testExceedMsgLimit(t *testing.T, e env) { te := newTest(t, e) maxMsgSize := 1024 te.maxServerMsgSize, te.maxClientMsgSize = newInt(maxMsgSize), newInt(maxMsgSize) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -2901,7 +2889,7 @@ func (s) TestPeerClientSide(t *testing.T) { func testPeerClientSide(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) peer := new(peer.Peer) @@ -2939,7 +2927,7 @@ func (s) TestPeerNegative(t *testing.T) { func testPeerNegative(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -2959,7 +2947,7 @@ func (s) TestPeerFailedRPC(t *testing.T) { func testPeerFailedRPC(t *testing.T, e env) { te := newTest(t, e) te.maxServerReceiveMsgSize = newInt(1 * 1024) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3013,7 +3001,7 @@ func (s) TestMetadataUnaryRPC(t *testing.T) { func testMetadataUnaryRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3058,7 +3046,7 @@ func (s) TestMetadataOrderUnaryRPC(t *testing.T) { func testMetadataOrderUnaryRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3095,7 +3083,7 @@ func (s) TestMultipleSetTrailerUnaryRPC(t *testing.T) { func testMultipleSetTrailerUnaryRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, multipleSetTrailer: true}.Svc()) + te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3132,7 +3120,7 @@ func (s) TestMultipleSetTrailerStreamingRPC(t *testing.T) { func testMultipleSetTrailerStreamingRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, multipleSetTrailer: true}.Svc()) + te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3167,7 +3155,7 @@ func (s) TestSetAndSendHeaderUnaryRPC(t *testing.T) { // To test header metadata is sent on SendHeader(). func testSetAndSendHeaderUnaryRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setAndSendHeader: true}.Svc()) + te.startServer(&testServer{security: e.security, setAndSendHeader: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3210,7 +3198,7 @@ func (s) TestMultipleSetHeaderUnaryRPC(t *testing.T) { // To test header metadata is sent when sending response. func testMultipleSetHeaderUnaryRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setHeaderOnly: true}.Svc()) + te.startServer(&testServer{security: e.security, setHeaderOnly: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3254,7 +3242,7 @@ func (s) TestMultipleSetHeaderUnaryRPCError(t *testing.T) { // To test header metadata is sent when sending status. func testMultipleSetHeaderUnaryRPCError(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setHeaderOnly: true}.Svc()) + te.startServer(&testServer{security: e.security, setHeaderOnly: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3297,7 +3285,7 @@ func (s) TestSetAndSendHeaderStreamingRPC(t *testing.T) { // To test header metadata is sent on SendHeader(). func testSetAndSendHeaderStreamingRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setAndSendHeader: true}.Svc()) + te.startServer(&testServer{security: e.security, setAndSendHeader: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3337,7 +3325,7 @@ func (s) TestMultipleSetHeaderStreamingRPC(t *testing.T) { // To test header metadata is sent when sending response. func testMultipleSetHeaderStreamingRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setHeaderOnly: true}.Svc()) + te.startServer(&testServer{security: e.security, setHeaderOnly: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3401,7 +3389,7 @@ func (s) TestMultipleSetHeaderStreamingRPCError(t *testing.T) { // To test header metadata is sent when sending status. func testMultipleSetHeaderStreamingRPCError(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, setHeaderOnly: true}.Svc()) + te.startServer(&testServer{security: e.security, setHeaderOnly: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3466,7 +3454,7 @@ func (s) TestMalformedHTTP2Metadata(t *testing.T) { func testMalformedHTTP2Metadata(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3509,7 +3497,7 @@ func testTransparentRetry(t *testing.T, e env) { } return ctx, nil } - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -3558,7 +3546,7 @@ func (s) TestCancel(t *testing.T) { func testCancel(t *testing.T, e env) { te := newTest(t, e) te.declareLogNoise("grpc: the client connection is closing; please retry") - te.startServer(testServer{security: e.security, unaryCallSleepTime: time.Second}.Svc()) + te.startServer(&testServer{security: e.security, unaryCallSleepTime: time.Second}) defer te.tearDown() cc := te.clientConn() @@ -3595,7 +3583,7 @@ func testCancelNoIO(t *testing.T, e env) { te := newTest(t, e) te.declareLogNoise("http2Client.notifyError got notified that the client transport was broken") te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -3604,7 +3592,7 @@ func testCancelNoIO(t *testing.T, e env) { // Start one blocked RPC for which we'll never send streaming // input. This will consume the 1 maximum concurrent streams, // causing future RPCs to hang. - ctx, cancelFirst := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancelFirst := context.WithCancel(context.Background()) _, err := tc.StreamingInputCall(ctx) if err != nil { t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, ", tc, err) @@ -3617,9 +3605,6 @@ func testCancelNoIO(t *testing.T, e env) { // succeeding. // TODO(bradfitz): add internal test hook for this (Issue 534) for { - if ctx.Err() != nil { - t.Fatal("timed out waiting to get deadline exceeded error") - } ctx, cancelSecond := context.WithTimeout(context.Background(), 50*time.Millisecond) _, err := tc.StreamingInputCall(ctx) cancelSecond() @@ -3687,7 +3672,7 @@ func (s) TestPingPong(t *testing.T) { func testPingPong(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3746,7 +3731,7 @@ func (s) TestMetadataStreamingRPC(t *testing.T) { func testMetadataStreamingRPC(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3823,7 +3808,7 @@ func (s) TestServerStreaming(t *testing.T) { func testServerStreaming(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3878,7 +3863,7 @@ func (s) TestFailedServerStreaming(t *testing.T) { func testFailedServerStreaming(t *testing.T, e env) { te := newTest(t, e) te.userAgent = failAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -3907,10 +3892,17 @@ func equalError(x, y error) bool { return x == y || (x != nil && y != nil && x.Error() == y.Error()) } -// concurrentSendStreamingOutputCall makes ten serial Send calls, sending payloads +// concurrentSendServer is a TestServiceServer whose +// StreamingOutputCall makes ten serial Send calls, sending payloads // "0".."9", inclusive. TestServerStreamingConcurrent verifies they // were received in the correct order, and that there were no races. -func concurrentSendStreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { +// +// All other TestServiceServer methods crash if called. +type concurrentSendServer struct { + testpb.TestServiceServer +} + +func (s concurrentSendServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { for i := 0; i < 10; i++ { stream.Send(&testpb.StreamingOutputCallResponse{ Payload: &testpb.Payload{ @@ -3930,7 +3922,7 @@ func (s) TestServerStreamingConcurrent(t *testing.T) { func testServerStreamingConcurrent(t *testing.T, e env) { te := newTest(t, e) - te.startServer(&testpb.TestServiceService{StreamingOutputCall: concurrentSendStreamingOutputCall}) + te.startServer(concurrentSendServer{}) defer te.tearDown() cc := te.clientConn() @@ -4011,7 +4003,7 @@ func (s) TestClientStreaming(t *testing.T) { func testClientStreaming(t *testing.T, e env, sizes []int) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4057,7 +4049,7 @@ func (s) TestClientStreamingError(t *testing.T) { func testClientStreamingError(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, earlyFail: true}.Svc()) + te.startServer(&testServer{security: e.security, earlyFail: true}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4102,7 +4094,7 @@ func testExceedMaxStreamsLimit(t *testing.T, e env) { "grpc: the connection is closing", ) te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -4142,7 +4134,7 @@ func testStreamsQuotaRecovery(t *testing.T, e env) { "grpc: the connection is closing", ) te.maxStream = 1 // Allows 1 live stream. - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -4212,7 +4204,7 @@ func testCompressServerHasNoSupport(t *testing.T, e env) { te.serverCompression = false te.clientCompression = false te.clientNopCompression = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4250,7 +4242,7 @@ func testCompressOK(t *testing.T, e env) { te := newTest(t, e) te.serverCompression = true te.clientCompression = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4311,7 +4303,7 @@ func (s) TestIdentityEncoding(t *testing.T) { func testIdentityEncoding(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4375,7 +4367,7 @@ func testUnaryClientInterceptor(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA te.unaryClientInt = failOkayRPC - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4401,7 +4393,7 @@ func failOkayStream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientC func testStreamClientInterceptor(t *testing.T, e env) { te := newTest(t, e) te.streamClientInt = failOkayStream - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4437,7 +4429,7 @@ func errInjector(ctx context.Context, req interface{}, info *grpc.UnaryServerInf func testUnaryServerInterceptor(t *testing.T, e env) { te := newTest(t, e) te.unaryServerInt = errInjector - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4467,7 +4459,7 @@ func fullDuplexOnly(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServ func testStreamServerInterceptor(t *testing.T, e env) { te := newTest(t, e) te.streamServerInt = fullDuplexOnly - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -4504,6 +4496,29 @@ func testStreamServerInterceptor(t *testing.T, e env) { } } +// funcServer implements methods of TestServiceServer using funcs, +// similar to an http.HandlerFunc. +// Any unimplemented method will crash. Tests implement the method(s) +// they need. +type funcServer struct { + testpb.TestServiceServer + unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) + streamingInputCall func(stream testpb.TestService_StreamingInputCallServer) error + fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error +} + +func (s *funcServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + return s.unaryCall(ctx, in) +} + +func (s *funcServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { + return s.streamingInputCall(stream) +} + +func (s *funcServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { + return s.fullDuplexCall(stream) +} + func (s) TestClientRequestBodyErrorUnexpectedEOF(t *testing.T) { for _, e := range listTestEnv() { testClientRequestBodyErrorUnexpectedEOF(t, e) @@ -4512,7 +4527,7 @@ func (s) TestClientRequestBodyErrorUnexpectedEOF(t *testing.T) { func testClientRequestBodyErrorUnexpectedEOF(t *testing.T, e env) { te := newTest(t, e) - ts := &testpb.TestServiceService{UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { errUnexpectedCall := errors.New("unexpected call func server method") t.Error(errUnexpectedCall) return nil, errUnexpectedCall @@ -4536,7 +4551,7 @@ func (s) TestClientRequestBodyErrorCloseAfterLength(t *testing.T) { func testClientRequestBodyErrorCloseAfterLength(t *testing.T, e env) { te := newTest(t, e) te.declareLogNoise("Server.processUnaryRPC failed to write status") - ts := &testpb.TestServiceService{UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { errUnexpectedCall := errors.New("unexpected call func server method") t.Error(errUnexpectedCall) return nil, errUnexpectedCall @@ -4560,7 +4575,7 @@ func (s) TestClientRequestBodyErrorCancel(t *testing.T) { func testClientRequestBodyErrorCancel(t *testing.T, e env) { te := newTest(t, e) gotCall := make(chan bool, 1) - ts := &testpb.TestServiceService{UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { gotCall <- true return new(testpb.SimpleResponse), nil }} @@ -4596,7 +4611,7 @@ func (s) TestClientRequestBodyErrorCancelStreamingInput(t *testing.T) { func testClientRequestBodyErrorCancelStreamingInput(t *testing.T, e env) { te := newTest(t, e) recvErr := make(chan error, 1) - ts := &testpb.TestServiceService{StreamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { + ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { _, err := stream.Recv() recvErr <- err return nil @@ -4638,7 +4653,7 @@ func testClientInitialHeaderEndStream(t *testing.T, e env) { // checking. handlerDone := make(chan struct{}) te := newTest(t, e) - ts := &testpb.TestServiceService{StreamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { + ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { defer close(handlerDone) // Block on serverTester receiving RST_STREAM. This ensures server has closed // stream before stream.Recv(). @@ -4682,7 +4697,7 @@ func testClientSendDataAfterCloseSend(t *testing.T, e env) { // checking. handlerDone := make(chan struct{}) te := newTest(t, e) - ts := &testpb.TestServiceService{StreamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { + ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { defer close(handlerDone) // Block on serverTester receiving RST_STREAM. This ensures server has closed // stream before stream.Recv(). @@ -4734,7 +4749,7 @@ func (s) TestClientResourceExhaustedCancelFullDuplex(t *testing.T) { func testClientResourceExhaustedCancelFullDuplex(t *testing.T, e env) { te := newTest(t, e) recvErr := make(chan error, 1) - ts := &testpb.TestServiceService{FullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { + ts := &funcServer{fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { defer close(recvErr) _, err := stream.Recv() if err != nil { @@ -4857,10 +4872,10 @@ func (s) TestFlowControlLogicalRace(t *testing.T) { defer lis.Close() s := grpc.NewServer() - testpb.RegisterTestServiceService(s, (&flowControlLogicalRaceServer{ + testpb.RegisterTestServiceServer(s, &flowControlLogicalRaceServer{ itemCount: itemCount, itemSize: itemSize, - }).Svc()) + }) defer s.Stop() go s.Serve(lis) @@ -4914,16 +4929,12 @@ func (s) TestFlowControlLogicalRace(t *testing.T) { } type flowControlLogicalRaceServer struct { + testpb.TestServiceServer + itemSize int itemCount int } -func (s *flowControlLogicalRaceServer) Svc() *testpb.TestServiceService { - return &testpb.TestServiceService{ - StreamingOutputCall: s.StreamingOutputCall, - } -} - func (s *flowControlLogicalRaceServer) StreamingOutputCall(req *testpb.StreamingOutputCallRequest, srv testpb.TestService_StreamingOutputCallServer) error { for i := 0; i < s.itemCount; i++ { err := srv.Send(&testpb.StreamingOutputCallResponse{ @@ -5066,6 +5077,9 @@ func (fw *filterWriter) Write(p []byte) (n int, err error) { // stubServer is a server that is easy to customize within individual test // cases. type stubServer struct { + // Guarantees we satisfy this interface; panics if unimplemented methods are called. + testpb.TestServiceServer + // Customizable implementations of server handlers. emptyCall func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) @@ -5087,12 +5101,16 @@ type stubServer struct { r *manual.Resolver } -func (ss *stubServer) Svc() *testpb.TestServiceService { - return &testpb.TestServiceService{ - EmptyCall: ss.emptyCall, - UnaryCall: ss.unaryCall, - FullDuplexCall: ss.fullDuplexCall, - } +func (ss *stubServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { + return ss.emptyCall(ctx, in) +} + +func (ss *stubServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + return ss.unaryCall(ctx, in) +} + +func (ss *stubServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { + return ss.fullDuplexCall(stream) } // Start starts the server and creates a client connected to it. @@ -5115,7 +5133,7 @@ func (ss *stubServer) Start(sopts []grpc.ServerOption, dopts ...grpc.DialOption) ss.cleanups = append(ss.cleanups, func() { lis.Close() }) s := grpc.NewServer(sopts...) - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) go s.Serve(lis) ss.cleanups = append(ss.cleanups, s.Stop) ss.s = s @@ -5474,7 +5492,7 @@ func testConfigurableWindowSize(t *testing.T, e env, wc windowSizeConfig) { te.clientInitialWindowSize = wc.clientStream te.clientInitialConnWindowSize = wc.clientConn - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -5524,7 +5542,7 @@ func (s) TestWaitForReadyConnection(t *testing.T) { func testWaitForReadyConnection(t *testing.T, e env) { te := newTest(t, e) te.userAgent = testAppUA - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() // Non-blocking dial. @@ -5575,7 +5593,7 @@ func testEncodeDoesntPanic(t *testing.T, e env) { te := newTest(t, e) erc := &errCodec{} te.customCodec = erc - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() te.customCodec = nil tc := testpb.NewTestServiceClient(te.clientConn()) @@ -5609,7 +5627,7 @@ func testSvrWriteStatusEarlyWrite(t *testing.T, e env) { if err != nil { t.Fatal(err) } - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) respParam := []*testpb.ResponseParameters{ @@ -5888,7 +5906,7 @@ func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) { } // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv). te1, ch1 := testServiceConfigSetupTD(t, e) - te1.startServer(testServer{security: e.security}.Svc()) + te1.startServer(&testServer{security: e.security}) defer te1.tearDown() ch1 <- sc @@ -5948,7 +5966,7 @@ func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) { te2, ch2 := testServiceConfigSetupTD(t, e) te2.maxClientReceiveMsgSize = newInt(1024) te2.maxClientSendMsgSize = newInt(1024) - te2.startServer(testServer{security: e.security}.Svc()) + te2.startServer(&testServer{security: e.security}) defer te2.tearDown() ch2 <- sc tc = testpb.NewTestServiceClient(te2.clientConn()) @@ -5997,7 +6015,7 @@ func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) { te3, ch3 := testServiceConfigSetupTD(t, e) te3.maxClientReceiveMsgSize = newInt(4096) te3.maxClientSendMsgSize = newInt(4096) - te3.startServer(testServer{security: e.security}.Svc()) + te3.startServer(&testServer{security: e.security}) defer te3.tearDown() ch3 <- sc tc = testpb.NewTestServiceClient(te3.clientConn()) @@ -6089,7 +6107,7 @@ func (s) TestMethodFromServerStream(t *testing.T) { func (s) TestInterceptorCanAccessCallOptions(t *testing.T) { e := tcpClearRREnv te := newTest(t, e) - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() type observedOptions struct { @@ -6200,7 +6218,7 @@ func testCompressorRegister(t *testing.T, e env) { te.serverCompression = false te.clientUseCompression = true - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -6258,7 +6276,7 @@ func (s) TestServeExitsWhenListenerClosed(t *testing.T) { s := grpc.NewServer() defer s.Stop() - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) lis, err := net.Listen("tcp", "localhost:0") if err != nil { @@ -6375,7 +6393,7 @@ func testClientDoesntDeadlockWhileWritingErrornousLargeMessages(t *testing.T, e te.userAgent = testAppUA smallSize := 1024 te.maxServerReceiveMsgSize = &smallSize - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1048576) @@ -6412,7 +6430,7 @@ func (s) TestRPCTimeout(t *testing.T) { func testRPCTimeout(t *testing.T, e env) { te := newTest(t, e) - te.startServer(testServer{security: e.security, unaryCallSleepTime: 500 * time.Millisecond}.Svc()) + te.startServer(&testServer{security: e.security, unaryCallSleepTime: 500 * time.Millisecond}) defer te.tearDown() cc := te.clientConn() @@ -6477,7 +6495,7 @@ func (s) TestDisabledIOBuffers(t *testing.T) { } s := grpc.NewServer(grpc.WriteBufferSize(0), grpc.ReadBufferSize(0)) - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) lis, err := net.Listen("tcp", "localhost:0") if err != nil { @@ -6535,7 +6553,7 @@ func testServerMaxHeaderListSizeClientUserViolation(t *testing.T, e env) { te := newTest(t, e) te.maxServerHeaderListSize = new(uint32) *te.maxServerHeaderListSize = 216 - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -6567,7 +6585,7 @@ func testClientMaxHeaderListSizeServerUserViolation(t *testing.T, e env) { te := newTest(t, e) te.maxClientHeaderListSize = new(uint32) *te.maxClientHeaderListSize = 1 // any header server sends will violate - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc := te.clientConn() @@ -6598,7 +6616,7 @@ func testServerMaxHeaderListSizeClientIntentionalViolation(t *testing.T, e env) te := newTest(t, e) te.maxServerHeaderListSize = new(uint32) *te.maxServerHeaderListSize = 512 - te.startServer(testServer{security: e.security}.Svc()) + te.startServer(&testServer{security: e.security}) defer te.tearDown() cc, dw := te.clientConnWithConnControl() @@ -6640,7 +6658,7 @@ func testClientMaxHeaderListSizeServerIntentionalViolation(t *testing.T, e env) te := newTest(t, e) te.maxClientHeaderListSize = new(uint32) *te.maxClientHeaderListSize = 200 - lw := te.startServerWithConnControl(testServer{security: e.security, setHeaderOnly: true}.Svc()) + lw := te.startServerWithConnControl(&testServer{security: e.security, setHeaderOnly: true}) defer te.tearDown() cc, _ := te.clientConnWithConnControl() tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} @@ -6687,10 +6705,10 @@ func (s) TestNetPipeConn(t *testing.T) { pl := testutils.NewPipeListener() s := grpc.NewServer() defer s.Stop() - ts := &testpb.TestServiceService{UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { return &testpb.SimpleResponse{}, nil }} - testpb.RegisterTestServiceService(s, ts) + testpb.RegisterTestServiceServer(s, ts) go s.Serve(pl) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -6715,18 +6733,7 @@ func testLargeTimeout(t *testing.T, e env) { te := newTest(t, e) te.declareLogNoise("Server.processUnaryRPC failed to write status") - maxTimeoutChan := make(chan time.Duration, 1) - ts := &testpb.TestServiceService{UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - maxTimeout := <-maxTimeoutChan - deadline, ok := ctx.Deadline() - timeout := time.Until(deadline) - minTimeout := maxTimeout - 5*time.Second - if !ok || timeout < minTimeout || timeout > maxTimeout { - t.Errorf("ctx.Deadline() = (now+%v), %v; want [%v, %v], true", timeout, ok, minTimeout, maxTimeout) - return nil, status.Error(codes.OutOfRange, "deadline error") - } - return &testpb.SimpleResponse{}, nil - }} + ts := &funcServer{} te.startServer(ts) defer te.tearDown() tc := testpb.NewTestServiceClient(te.clientConn()) @@ -6738,7 +6745,17 @@ func testLargeTimeout(t *testing.T, e env) { } for i, maxTimeout := range timeouts { - maxTimeoutChan <- maxTimeout + ts.unaryCall = func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + deadline, ok := ctx.Deadline() + timeout := time.Until(deadline) + minTimeout := maxTimeout - 5*time.Second + if !ok || timeout < minTimeout || timeout > maxTimeout { + t.Errorf("ctx.Deadline() = (now+%v), %v; want [%v, %v], true", timeout, ok, minTimeout, maxTimeout) + return nil, status.Error(codes.OutOfRange, "deadline error") + } + return &testpb.SimpleResponse{}, nil + } + ctx, cancel := context.WithTimeout(context.Background(), maxTimeout) defer cancel() @@ -6761,11 +6778,11 @@ func (s) TestGoAwayThenClose(t *testing.T) { } s1 := grpc.NewServer() defer s1.Stop() - ts := &testpb.TestServiceService{ - UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { + ts := &funcServer{ + unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { return &testpb.SimpleResponse{}, nil }, - FullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { + fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { // Wait forever. _, err := stream.Recv() if err == nil { @@ -6774,7 +6791,7 @@ func (s) TestGoAwayThenClose(t *testing.T) { return err }, } - testpb.RegisterTestServiceService(s1, ts) + testpb.RegisterTestServiceServer(s1, ts) go s1.Serve(lis1) conn2Established := grpcsync.NewEvent() @@ -6784,7 +6801,7 @@ func (s) TestGoAwayThenClose(t *testing.T) { } s2 := grpc.NewServer() defer s2.Stop() - testpb.RegisterTestServiceService(s2, ts) + testpb.RegisterTestServiceServer(s2, ts) go s2.Serve(lis2) r := manual.NewBuilderWithScheme("whatever") @@ -6854,7 +6871,7 @@ func (lis notifyingListener) Accept() (net.Conn, error) { func (s) TestRPCWaitsForResolver(t *testing.T) { te := testServiceConfigSetup(t, tcpClearRREnv) - te.startServer(testServer{security: tcpClearRREnv.security}.Svc()) + te.startServer(&testServer{security: tcpClearRREnv.security}) defer te.tearDown() r := manual.NewBuilderWithScheme("whatever") diff --git a/test/goaway_test.go b/test/goaway_test.go index 1e00976bc14..55f79ebc854 100644 --- a/test/goaway_test.go +++ b/test/goaway_test.go @@ -48,7 +48,7 @@ func (s) TestGracefulClientOnGoAway(t *testing.T) { s := grpc.NewServer(grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: maxConnAge})) defer s.Stop() - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) lis, err := net.Listen("tcp", "localhost:0") if err != nil { diff --git a/test/gracefulstop_test.go b/test/gracefulstop_test.go index 1f5f1e705cb..3da75ea1b51 100644 --- a/test/gracefulstop_test.go +++ b/test/gracefulstop_test.go @@ -117,7 +117,7 @@ func (s) TestGracefulStop(t *testing.T) { }, } s := grpc.NewServer() - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) // 1. Start Server wg := sync.WaitGroup{} diff --git a/test/grpc_testing/test_grpc.pb.go b/test/grpc_testing/test_grpc.pb.go index 45ae6552513..915eafd82f9 100644 --- a/test/grpc_testing/test_grpc.pb.go +++ b/test/grpc_testing/test_grpc.pb.go @@ -47,10 +47,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient { return &testServiceClient{cc} } -var testServiceEmptyCallStreamDesc = &grpc.StreamDesc{ - StreamName: "EmptyCall", -} - func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { out := new(Empty) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) @@ -60,10 +56,6 @@ func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...gr return out, nil } -var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{ - StreamName: "UnaryCall", -} - func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { out := new(SimpleResponse) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) @@ -73,13 +65,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op return out, nil } -var testServiceStreamingOutputCallStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingOutputCall", - ServerStreams: true, -} - func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceStreamingOutputCallStreamDesc, "/grpc.testing.TestService/StreamingOutputCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...) if err != nil { return nil, err } @@ -110,13 +97,8 @@ func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallRespo return m, nil } -var testServiceStreamingInputCallStreamDesc = &grpc.StreamDesc{ - StreamName: "StreamingInputCall", - ClientStreams: true, -} - func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceStreamingInputCallStreamDesc, "/grpc.testing.TestService/StreamingInputCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...) if err != nil { return nil, err } @@ -149,14 +131,8 @@ func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCal return m, nil } -var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{ - StreamName: "FullDuplexCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...) if err != nil { return nil, err } @@ -186,14 +162,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, return m, nil } -var testServiceHalfDuplexCallStreamDesc = &grpc.StreamDesc{ - StreamName: "HalfDuplexCall", - ServerStreams: true, - ClientStreams: true, -} - func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, testServiceHalfDuplexCallStreamDesc, "/grpc.testing.TestService/HalfDuplexCall", opts...) + stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...) if err != nil { return nil, err } @@ -223,82 +193,110 @@ func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, return m, nil } -// TestServiceService is the service API for TestService service. -// Fields should be assigned to their respective handler implementations only before -// RegisterTestServiceService is called. Any unassigned fields will result in the -// handler for that method returning an Unimplemented error. -type TestServiceService struct { +// TestServiceServer is the server API for TestService service. +// All implementations must embed UnimplementedTestServiceServer +// for forward compatibility +type TestServiceServer interface { // One empty request followed by one empty response. - EmptyCall func(context.Context, *Empty) (*Empty, error) + EmptyCall(context.Context, *Empty) (*Empty, error) // One request followed by one response. // The server returns the client payload as-is. - UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) + UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) // One request followed by a sequence of responses (streamed download). // The server returns the payload with client desired type and sizes. - StreamingOutputCall func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error + StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error // A sequence of requests followed by one response (streamed upload). // The server returns the aggregated size of client payload as the result. - StreamingInputCall func(TestService_StreamingInputCallServer) error + StreamingInputCall(TestService_StreamingInputCallServer) error // A sequence of requests with each request served by the server immediately. // As one request could lead to multiple responses, this interface // demonstrates the idea of full duplexing. - FullDuplexCall func(TestService_FullDuplexCallServer) error + FullDuplexCall(TestService_FullDuplexCallServer) error // A sequence of requests followed by a sequence of responses. // The server buffers all the client requests and then serves them in order. A // stream of responses are returned to the client when the server starts with // first request. - HalfDuplexCall func(TestService_HalfDuplexCallServer) error + HalfDuplexCall(TestService_HalfDuplexCallServer) error + mustEmbedUnimplementedTestServiceServer() +} + +// UnimplementedTestServiceServer must be embedded to have forward compatible implementations. +type UnimplementedTestServiceServer struct { +} + +func (UnimplementedTestServiceServer) EmptyCall(context.Context, *Empty) (*Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") +} +func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") +} +func (UnimplementedTestServiceServer) StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented") +} +func (UnimplementedTestServiceServer) StreamingInputCall(TestService_StreamingInputCallServer) error { + return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented") +} +func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error { + return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") +} +func (UnimplementedTestServiceServer) HalfDuplexCall(TestService_HalfDuplexCallServer) error { + return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented") +} +func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {} + +// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to TestServiceServer will +// result in compilation errors. +type UnsafeTestServiceServer interface { + mustEmbedUnimplementedTestServiceServer() +} + +func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { + s.RegisterService(&_TestService_serviceDesc, srv) } -func (s *TestServiceService) emptyCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Empty) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.EmptyCall(ctx, in) + return srv.(TestServiceServer).EmptyCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.TestService/EmptyCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.EmptyCall(ctx, req.(*Empty)) + return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) } return interceptor(ctx, in, info, handler) } -func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + +func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SimpleRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return s.UnaryCall(ctx, in) + return srv.(TestServiceServer).UnaryCall(ctx, in) } info := &grpc.UnaryServerInfo{ - Server: s, + Server: srv, FullMethod: "/grpc.testing.TestService/UnaryCall", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return s.UnaryCall(ctx, req.(*SimpleRequest)) + return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) } return interceptor(ctx, in, info, handler) } -func (s *TestServiceService) streamingOutputCall(_ interface{}, stream grpc.ServerStream) error { + +func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(StreamingOutputCallRequest) if err := stream.RecvMsg(m); err != nil { return err } - return s.StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} -func (s *TestServiceService) streamingInputCall(_ interface{}, stream grpc.ServerStream) error { - return s.StreamingInputCall(&testServiceStreamingInputCallServer{stream}) -} -func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error { - return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} -func (s *TestServiceService) halfDuplexCall(_ interface{}, stream grpc.ServerStream) error { - return s.HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) + return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) } type TestService_StreamingOutputCallServer interface { @@ -314,6 +312,10 @@ func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallRespon return x.ServerStream.SendMsg(m) } +func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream}) +} + type TestService_StreamingInputCallServer interface { SendAndClose(*StreamingInputCallResponse) error Recv() (*StreamingInputCallRequest, error) @@ -336,6 +338,10 @@ func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest return m, nil } +func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) +} + type TestService_FullDuplexCallServer interface { Send(*StreamingOutputCallResponse) error Recv() (*StreamingOutputCallRequest, error) @@ -358,6 +364,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, e return m, nil } +func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) +} + type TestService_HalfDuplexCallServer interface { Send(*StreamingOutputCallResponse) error Recv() (*StreamingOutputCallRequest, error) @@ -380,77 +390,42 @@ func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, e return m, nil } -// RegisterTestServiceService registers a service implementation with a gRPC server. -func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { - srvCopy := *srv - if srvCopy.EmptyCall == nil { - srvCopy.EmptyCall = func(context.Context, *Empty) (*Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") - } - } - if srvCopy.UnaryCall == nil { - srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") - } - } - if srvCopy.StreamingOutputCall == nil { - srvCopy.StreamingOutputCall = func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented") - } - } - if srvCopy.StreamingInputCall == nil { - srvCopy.StreamingInputCall = func(TestService_StreamingInputCallServer) error { - return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented") - } - } - if srvCopy.FullDuplexCall == nil { - srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error { - return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented") - } - } - if srvCopy.HalfDuplexCall == nil { - srvCopy.HalfDuplexCall = func(TestService_HalfDuplexCallServer) error { - return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented") - } - } - sd := grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: srvCopy.emptyCall, - }, - { - MethodName: "UnaryCall", - Handler: srvCopy.unaryCall, - }, +var _TestService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.testing.TestService", + HandlerType: (*TestServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "EmptyCall", + Handler: _TestService_EmptyCall_Handler, }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingOutputCall", - Handler: srvCopy.streamingOutputCall, - ServerStreams: true, - }, - { - StreamName: "StreamingInputCall", - Handler: srvCopy.streamingInputCall, - ClientStreams: true, - }, - { - StreamName: "FullDuplexCall", - Handler: srvCopy.fullDuplexCall, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "HalfDuplexCall", - Handler: srvCopy.halfDuplexCall, - ServerStreams: true, - ClientStreams: true, - }, + { + MethodName: "UnaryCall", + Handler: _TestService_UnaryCall_Handler, }, - Metadata: "test/grpc_testing/test.proto", - } - - s.RegisterService(&sd, nil) + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "StreamingOutputCall", + Handler: _TestService_StreamingOutputCall_Handler, + ServerStreams: true, + }, + { + StreamName: "StreamingInputCall", + Handler: _TestService_StreamingInputCall_Handler, + ClientStreams: true, + }, + { + StreamName: "FullDuplexCall", + Handler: _TestService_FullDuplexCall_Handler, + ServerStreams: true, + ClientStreams: true, + }, + { + StreamName: "HalfDuplexCall", + Handler: _TestService_HalfDuplexCall_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "test/grpc_testing/test.proto", } diff --git a/test/healthcheck_test.go b/test/healthcheck_test.go index c8a3796048b..0a60f8c927a 100644 --- a/test/healthcheck_test.go +++ b/test/healthcheck_test.go @@ -140,7 +140,7 @@ func setupServer(sc *svrConfig) (s *grpc.Server, lis net.Listener, ts *testHealt ts = newTestHealthServer() } healthgrpc.RegisterHealthServer(s, ts) - testpb.RegisterTestServiceService(s, testServer{}.Svc()) + testpb.RegisterTestServiceServer(s, &testServer{}) go s.Serve(lis) return s, lis, ts, s.Stop, nil } diff --git a/test/local_creds_test.go b/test/local_creds_test.go index 86969c15d33..b55b73bdcbc 100644 --- a/test/local_creds_test.go +++ b/test/local_creds_test.go @@ -64,7 +64,7 @@ func testLocalCredsE2ESucceed(network, address string) error { s := grpc.NewServer(sopts...) defer s.Stop() - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) lis, err := net.Listen(network, address) if err != nil { @@ -162,7 +162,7 @@ func testLocalCredsE2EFail(dopts []grpc.DialOption) error { s := grpc.NewServer(sopts...) defer s.Stop() - testpb.RegisterTestServiceService(s, ss.Svc()) + testpb.RegisterTestServiceServer(s, ss) lis, err := net.Listen("tcp", "localhost:0") if err != nil {