Git Product home page Git Product logo

graphql-analyzer's Introduction

GraphQL::Analyzer

Build Status Gem Version

GraphQL Analyzer is a GraphQL extension for tracking datastore queries.

Installation

Add this line to your application's Gemfile:

gem 'graphql-analyzer'

And then execute:

$ bundle

Or install it yourself as:

$ gem install graphql-analyzer

Usage

Add an instance of GraphQL::Analyzer to your schema, instantiate it with a list of instrumentations to capture different datastore queries.

Analyzer

Add 'GraphQL::Analyzer' to your schema:

require 'graphql/analyzer'

Schema = GraphQL::Schema.define do
  query QueryType
  use(
      GraphQL::Analyzer.new(
        GraphQL::Analyzer::Instrumentation::Mysql.new,
        GraphQL::Analyzer::Instrumentation::Postgresql.new
      )
  )
end

Response Format

The GraphQL specification allows servers to include additional information as part of the response under an extensions key:

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

GraphQL Analyzer exposes datastore query data for an individual request under a analyzer key in extensions:

{
  "data": <>,
  "errors": <>,
  "extensions": {
    "analyzer": {
      "version": 1,
      "execution": {
        "resolvers": [
          {
            "path": [
              "node"
            ],
            "adapter": "sqlite3",
            "parentType": "Query",
            "fieldName": "node",
            "returnType": "Node",
            "details": {
              "root": "EXPLAIN for: SELECT  \"users\".* FROM \"users\" WHERE \"users\".\"id\" = ? LIMIT ? [[\"id\", 7], [\"LIMIT\", 1]",
              "explained_queries": [
                {
                  "select_id": "0",
                  "order": "0",
                  "from": "0",
                  "details": "SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?)"
                }
              ]
            }
          }
        ]
      }
    }
  }
}

Instrumentation

There are some common instruments already implemented that should work right away.

  • Sqlite3
  • Mysql
  • Postgresql

Check lib/graphql/analyzer/instrumentation for the full list.

To write your own custom instrumentation, your object needs to respond to #instrument(type, field) and return a lambda that accepts three parameters, object, arguments, and context, and returns the original field value. It should also add any queries captured to the context.

module GraphQL
  class Analyzer
    module Instrumentation
      class MyCustomInstrumentation < Base
        def instrument(type, field)
          ->(obj, args, ctx) do
            ### OMITTED ###
              ctx['graphql-analyzer']['resolvers'] << {
                'adapter' => 'My Custom Adapter',
                'path' => ctx.path,
                'parentType' => type.name,
                'fieldName' => field.name,
                'returnType' => field.type.to_s,
                'details' => 'My Adapter Specific Information'
              }
              ### OMITTED ###
          end
        end
      end
    end
  end
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/GraphQL-Query-Planner/graphql-analyzer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

graphql-analyzer's People

Contributors

derekstride avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

graphql-analyzer's Issues

Multi datastore integration failures, wrong connection for explain

When integrating the analyzer with a active record project that has a specific table with a different datastore connection from the default ActiveRecord::Base, trying to execute the explain query sends the request to the wrong datastore connection.

Failures:

  1) tables backed by specific datastore connections parses each query only once
     Failure/Error: result["extensions"] ||= {}

     NoMethodError:
       undefined method `[]' for nil:NilClass
     # ./lib/graphql/analyzer.rb:34:in `after_query'
     # ./spec/graphql/analyzer/instrumentation/active_record_spec.rb:98:in `block (2 levels) in <top (required)>'
     # ./spec/graphql/analyzer/instrumentation/active_record_spec.rb:104:in `block (2 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # Mysql2::Error:
     #   You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.* FROM "pg_users" WHERE "pg_users"."id" = $1 LIMIT $2' at line 1
     #   ./lib/graphql/analyzer/instrumentation/base.rb:15:in `block in instrument'

Finished in 59 minutes 28 seconds (files took 1.02 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/graphql/analyzer/instrumentation/active_record_spec.rb:103 # tables backed by specific datastore connections parses each query only once

Statistics per instrumentation

The idea is to let each instrumentation define its own set of additional statistics. For example it make sense to show a query count for the MysQL instrumentation but maybe not so much for ElasticSearch. This change will need some refactor in the gem in order to allow this but it provides more flexibility.

cc\ @r-deleon

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.