Home > Blockchain >  gRPC Unary Call Connection State Check on Server
gRPC Unary Call Connection State Check on Server

Time:08-09

I have an unary gRPC call that can take up to few minute to be processed on my Go gRPC server (involves human agent on the mobile APP). I would like to know if there is a way to check if the connection has been terminated on the client side before sending the response.

I found the solution for ServerStreaming case with Context Status.Done channel, but it does not work for my Unary RPC.

Below is the signature of the function where the control should be made:

func (*Server) EndpointName(ctx context.Context, in *pb.EndpointRequest) (*pb.EndpointResponse, error) {

CodePudding user response:

As per the function definition shown in your question, the endpoint function is passed a context (ctx context.Context). If the connection drops the context will be cancelled.

For example I can modify the helloworld example so that it simulates a long running job:

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    select {
    case <-ctx.Done():
        fmt.Println("Context is done:", ctx.Err())
        return nil, status.Error(codes.Canceled, "does not matter as nothing will ever get this anyway...")
    case <-time.After(time.Minute):
        // This simulates a long-running process. In reality the process itself should be checking the context
    }
    return &pb.HelloReply{}, nil
}

To test this I altered greeter_client to call the function and then panic() whilst waiting for the response; the server outputs:

2022/08/08 08:16:57 server listening at [::]:50051
Context is done: context canceled
  • Related