11

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
}
martin
  • 338
  • 1
  • 3
  • 5
  • I have a similar question but with a Kotlin for Android client. Could you find any solution to keeping the connection open? – Daniel Jul 08 '20 at 09:22

2 Answers2

19

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.

Seb
  • 888
  • 12
  • 20
0

Please check if the connection is not nil and then proceed to close it.

As per the error defined in the close() the ErrClientConnClosing error is occurring if the connection is nil .

Code ref : https://github.com/grpc/grpc-go/blob/master/clientconn.go#L1064

if c.conn != nil { errs := c.Close() }

Anupam
  • 131
  • 2
  • 6