Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang gRPC can't keep alive: the client connection is closing

Tags:

go

grpc

graphql

Hi I'm trying to connect a gRPC client to the server but even though the connection is succesful I get the following error when querying it from the graphql resolvers. However if I dial directly from the resolver everything works so it has to do with the client not leaving the connection open.

rpc error: code = Canceled desc = grpc: the client connection is closing

client.go

var kacp = keepalive.ClientParameters{
    Time:                10 * time.Second, // send pings every 10 seconds if there is no activity
    Timeout:             time.Second,      // wait 1 second for ping back
    PermitWithoutStream: true,             // send pings even without active streams
}

func gqlHandler() http.HandlerFunc {

    conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure(), 
    grpc.WithKeepaliveParams(kacp),
    grpc.WithBlock())

    if err != nil {
        panic(err)
    }
    defer conn.Close()

    db := proto.NewPlatformDBClient(conn)

    gh := handler.GraphQL(platform.NewExecutableSchema(platform.Config{Resolvers: &platform.Resolver{
        DB: db,
    }}))

    gh = cors.Disable(gh)

    return gh
}
like image 575
martin Avatar asked Jun 18 '20 02:06

martin


1 Answers

Its because the defer conn.Close() command will be executed before the connection is even used.

From the go blog

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns.

So you would remove the line defer conn.Close() and close the connection after it is not used anymore.

like image 88
Seb Avatar answered Sep 20 '22 09:09

Seb