gRPC 可以实现 nil 服务器消息吗?

col*_*tor 6 go grpc grpc-go

在下面的gRPC-client代码中,第二个是if必要的吗?

status, err := cli.GetStatus(ctx, &empty.Empty{})
if err != nil {
    return err
}

if status == nil {
    // this should NEVER happen - right?
    return fmt.Errorf("nil Status result returned") 
}
Run Code Online (Sandbox Code Playgroud)

go 直觉上,为了以防万一,应该始终检查 nil 。但是,有一个运行时检查来捕获任何客户端到服务器的nil使用情况,例如

status, err := cli.GetStatus(ctx, nil) // <- runtime error

if err != nil {
    // "rpc error: code = Internal desc = grpc: error while marshaling: proto: Marshal called with nil"
    return err
}
Run Code Online (Sandbox Code Playgroud)

那么是否存在类似的服务器到客户端运行时保证,从而消除检查的需要status == nil

col*_*tor 8

使用一个人为的服务器示例进一步调查:

func (s *mygRPC) GetStatus(context.Context, *empty.Empty) (*pb.Status, error) {
    log.Println("cli: GetStatus()")

    //return &pb.Status{}, nil
    return nil, nil // <- can server return a nil status message (with nil error)
}
Run Code Online (Sandbox Code Playgroud)

并测试客户端/服务器反应:

客户:

ERROR: rpc error: code = Internal desc = grpc: error while marshaling: proto: Marshal called with nil
Run Code Online (Sandbox Code Playgroud)

服务器:

2019/05/14 16:09:50 cli: GetStatus()
ERROR: 2019/05/14 16:09:50 grpc: server failed to encode response:  rpc error: code = Internal desc = grpc: error while marshaling: proto: Marshal called with nil
Run Code Online (Sandbox Code Playgroud)

因此,即使有人想要合法地返回零值,gRPC传输也不会允许。

注意:服务器端代码仍然按预期执行,但就客户端而言,调用gRPC失败。

结论:有效的 ( err==nil) 服务器响应将始终返回有效的(非nil)消息。


编辑:

检查源可以揭示捕获消息的gRPC位置:nil

服务器.go

func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error {
    data, err := encode(s.getCodec(stream.ContentSubtype()), msg)
    if err != nil {
        grpclog.Errorln("grpc: server failed to encode response: ", err)
        return err
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

rpc_util.go

func encode(c baseCodec, msg interface{}) ([]byte, error) {
    if msg == nil { // NOTE: typed nils will not be caught by this check
        return nil, nil
    }
    b, err := c.Marshal(msg)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这一行的注释很关键:

if msg == nil { // NOTE: typed nils will not be caught by this check }
Run Code Online (Sandbox Code Playgroud)

因此,如果要对我们键入的 nil 使用反射,reflect.ValueOf(msg).IsNil()则会返回true。出现以下c.Marshal(msg)错误 - 并且调用未能向客户端发送消息响应。