Stanley
Stanley

Reputation: 2806

Setting timeouts for grpc functions in node js

Trying to create a timeout for grpc connection in the event that the server grpc implementation doesn't specify a callback function, however it seems that no matter what is specified in the options (new Date().getSeconds()+5) the client doesn't terminate the connection

    function hello (call, callback) {
        console.log(call.request.message)
    }
    server.addService(client.Hello.service, {hello: hello});
    server.bind('localhost:50051', grpc.ServerCredentials.createInsecure());
    server.start();
    grpcClient = new client.Hello('localhost:50051',
        grpc.credentials.createInsecure(),{deadline: new Date().getSeconds()+5}); //


    grpcClient.hello({message: "abc"}, function(err, response) {
        console.log(response) // doesn't reach here because function hello doesn't callback
    })

Upvotes: 8

Views: 12182

Answers (3)

piyush pruthi
piyush pruthi

Reputation: 106

You can also set rpc deadline as:

function getRPCDeadline(rpcType) {

    timeAllowed = 5000
    switch(rpcType) {

        case 1:
            timeAllowed = 5000  // LIGHT RPC
            break

        case 2 :
            timeAllowed = 7000  // HEAVY RPC
            break

        default :
            console.log("Invalid RPC Type: Using Default Timeout")

    }

    return new Date( Date.now() + timeAllowed )

}

And then use this function while calling any rpc:

var deadline = getRPCDeadline(1)

grpcClient.hello({message: "abc"},{deadline: deadline}, function(err, response) {
    console.log(err)
    console.log(response)
});

Upvotes: 9

Manish Pokhriyal
Manish Pokhriyal

Reputation: 11

https://grpc.io/docs/guides/concepts.html#cancelling-rpcs

Deadlines/Timeouts

gRPC allows clients to specify how long they are willing to wait for an RPC to complete before the RPC is terminated with the error DEADLINE_EXCEEDED. On the server side, the server can query to see if a particular RPC has timed out, or how much time is left to complete the RPC.

How the deadline or timeout is specified varies from language to language - for example, not all languages have a default deadline, some language APIs work in terms of a deadline (a fixed point in time), and some language APIs work in terms of timeouts (durations of time).

Upvotes: 0

Stanley
Stanley

Reputation: 2806

Ok seems like got it working with the below code:

var timeout_in_seconds = 5
var timeout = new Date().setSeconds(new Date().getSeconds() + timeout_in_seconds)

grpcClient.hello({message: "abc"},{deadline: timeout}, function(err, response) {
    console.log(err)
    console.log(response)
});

Upvotes: 5

Related Questions