Daniel
Daniel

Reputation: 311

GraphQL-java query timeout

Is there a way to set a timeout on query execution with the GraphQL-java implementation? That seems like a fairly basic security thing that's recommended by the GraphQL docs, but I can't find anything for it.

Upvotes: 1

Views: 4086

Answers (1)

felipe_gdr
felipe_gdr

Reputation: 1088

You can use GraphQL Java instrumentation for that.

The example bellow sets a timeout of 3 seconds for every data fetcher. You can use the instance of InstrumentationFieldFetchParameters passed in to apply the timeout to specific data fetchers (maybe one up on the query structure if you want a timeout for the whole query).

public class TimeoutInstrumentation extends SimpleInstrumentation {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
            DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters
    ) {
        return environment ->
            Observable.fromCallable(() -> dataFetcher.get(environment))
                .subscribeOn(Schedulers.computation())
                .timeout(3, TimeUnit.SECONDS)
                .blockingFirst();
    }
}

You can also use 2 existing instrumentations to achieve other checks mentioned in the page you've posted:

There's also the option of setting up a timeout at the request level. This is out of GraphQL Java's jurisdiction though. If you're using Spring as the http server you can setup a global request timeout using the spring.mvc.async.request-timeout application property. I'm pretty sure any other web server would have a similar property as well.

Upvotes: 4

Related Questions