question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Offer a way to calculate and limit the total cost of a query

See original GitHub issue

When offering a public API there’s the problem of malicious clients preparing intentionally expensive queries. For example one could abuse mutually related objects to arbitrarily make a query more expensive: book -> author -> books -> author -> books -> …and so on.

I’d like to request a method to evaluate the estimated cost of query before actually executing any resolvers and a way to prevent execution of queries with the estimate cost above a certain threshold (ideally in a programmatic fashion so we could for example vary the limits depending on the currently logged in user’s role).

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:13
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

19reactions
jkimbocommented, Jun 25, 2018

Ah sorry I missed that part. As far as I know there isn’t an “official” way of doing this but I’ve been playing around with then new backends feature that @syrusakbary introduced in graphql-core (https://github.com/graphql-python/graphql-core/pull/185) and I think this would be a great use case for it.

You should be able to do something like this with graphql-core 2.1rc:

from graphql.backend.core import GraphQLCoreBackend

def measure_depth(selection_set, level=1):
    max_depth = level
    for field in selection_set.selections:
        if field.selection_set:
            new_depth = measure_depth(field.selection_set, level=level + 1)
            if new_depth > max_depth:
                max_depth = new_depth
    return max_depth

class DepthAnalysisBackend(GraphQLCoreBackend):
    def document_from_string(self, schema, document_string):
        document = super().document_from_string(schema, document_string)
        ast = document.document_ast
        for definition in ast.definitions:
            # We are only interested in queries
            if definition.operation != 'query':
                continue

            depth = measure_depth(definition.selection_set)
            if depth > 3: # set your depth max here
                raise Exception('Query is too complex')

        return document

Then when you’re executing the following query it will bail out before trying to execute the query:

query_string = '''
    query {
		myFavouriteBook {
			author {
				bestBook {
					author {
						name
					}
				}
			}
		}
    }
'''

backend = DepthAnalysisBackend()
schema = graphene.Schema(query=Query)
result = schema.execute(query_string, backend=backend)

assert result.errors

I think there is a lot more that could be done here (like being able to assign complexity values to each field) but hopefully this helps you for now.

5reactions
patryscommented, Apr 21, 2022

Middleware is a poor fit because middleware is executed for each and every field resolver. For anyone interested, here’s how we solved it in our codebase:

https://github.com/saleor/saleor/blob/fa288358ab8dfecb0f862c12edbc512ad0f3f000/saleor/graphql/views.py#L296-L302

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Create a Calculation Query in Microsoft Access
In this tutorial, we will teach you how to create a calculation query in Microsoft access.Don't forget to check out our site ...
Read more >
Estimate storage and query costs | BigQuery - Google Cloud
Estimate costs of queries with Cloud console Query Validator, bq command-line tool, dryRun in APIs, Google Cloud Pricing Calculator, and the client libraries....
Read more >
What Is The Cost In PostgreSQL EXPLAIN Query - ScaleGrid
It picks the plan with the lowest overall cost, based on some configurable constants and some statistics it has gathered.
Read more >
Mysql query to calculate total cost - Stack Overflow
if the holidays were not adjacent (like 04-27 to 04-29 ), do you want one record or two in the resultset? · With...
Read more >
Calculate query charges for Amazon Redshift Spectrum
How do I calculate the Redshift Spectrum query usage or cost, and what are some best practices to reduce the charges?
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found