Giter Site home page Giter Site logo

uniiverse / apollo-tracing-ruby Goto Github PK

View Code? Open in Web Editor NEW
85.0 2.0 10.0 49 KB

[Maintainers Wanted] Ruby implementation of GraphQL trace data in the Apollo Tracing format

License: MIT License

Ruby 90.20% Shell 1.36% Makefile 8.44%
graphql ruby apollo-tracing graphql-ruby apollo-engine

apollo-tracing-ruby's Introduction

Apollo Tracing

Build Status Latest Version

Ruby implementation of GraphQL trace data in the Apollo Tracing format.

Contents

Installation

Add this line to your application's Gemfile:

gem 'apollo-tracing'

And then execute:

$ bundle

Or install it yourself as:

$ gem install apollo-tracing

Usage

Define a GraphQL schema:

# Define a type
PostType = GraphQL::ObjectType.define do
  name "Post"

  field :id, !types.ID
  field :title, !types.String
end

# Define a query
QueryType = GraphQL::ObjectType.define do
  name "Query"

  field :posts, !types[PostType] do
    argument :user_id, !types.ID
    resolve ->(obj, args, ctx) { Post.where(user_id: args[:user_id]) }
  end
end

# Define a schema
Schema = GraphQL::Schema.define do
  query QueryType
end

# Execute query
query = "
  query($user_id: ID!) {
    posts(user_id: $user_id) {
      id
      title
    }
  }
"
Schema.execute(query, variables: { user_id: 1 })

Tracing

Add 'ApolloTracing' to your schema:

require "apollo/tracing"

Schema = GraphQL::Schema.define do
  query QueryType
  use ApolloTracing.new
end

Now your response should look something like:

{
   "data":{
      "posts":[
         {
            "id":"1",
            "title":"Post Title"
         }
      ]
   },
   "extensions":{
      "tracing":{
         "version":1,
         "startTime":"2017-08-25T19:55:04.821Z",
         "endTime":"2017-08-25T19:55:04.823Z",
         "duration":1702785,
         "execution":{
            "resolvers":[
               {
                  "path":[
                     "posts"
                  ],
                  "parentType":"Query",
                  "fieldName":"posts",
                  "returnType":"[Post!]!",
                  "startOffset":1451015,
                  "duration":15735
               },
               {
                  "path":[
                     "posts",
                     0,
                     "id"
                  ],
                  "parentType":"Post",
                  "fieldName":"id",
                  "returnType":"ID!",
                  "startOffset":1556873,
                  "duration":6914
               },
               {
                  "path":[
                     "posts",
                     0,
                     "title"
                  ],
                  "parentType":"Post",
                  "fieldName":"title",
                  "returnType":"String!",
                  "startOffset":1604795,
                  "duration":4053
               },
               {
                  "path":[
                     "posts",
                     0,
                     "user_id"
                  ],
                  "parentType":"Post",
                  "fieldName":"user_id",
                  "returnType":"ID!",
                  "startOffset":1642942,
                  "duration":3814
               }
            ]
         }
      }
   }
}

Engine Proxy

Now you can start using the Apollo Engine service. Here is the general architecture overview of a sidecar mode – Proxy runs next to your application server:

 -----------------    request     -----------------    request     -----------------
|                 | -----------> |                 | -----------> |                 |
|     Client      |              |  Engine Proxy   |              |   Application   |
|                 | <----------- |                 | <----------- |                 |
 -----------------    response    -----------------    response    -----------------
                                          |
                                          |
                          GraphQL tracing | from response
                                          |
                                          ˅
                                  -----------------
                                 |                 |
                                 |  Apollo Engine  |
                                 |                 |
                                  -----------------

ApolloTracing gem comes with the Apollo Engine Proxy binary written in Go. To configure the Proxy create a Proxy config file:

# config/apollo-engine-proxy.json

{
  "apiKey": "service:YOUR_ENGINE_API_KEY",
  "logging": { "level": "INFO" },
  "origins": [{
    "http": { "url": "http://localhost:3000/graphql" }
  }],
  "frontends": [{
    "host": "localhost", "port": 3001, "endpoints": ["/graphql"]
  }]
}
  • apiKey – get this on your Apollo Engine home page.
  • logging.level – a log level for the Proxy ("INFO", "DEBUG" or "ERROR").
  • origins – a list of URLs with your GraphQL endpoints in the Application.
  • frontends – an address on which the Proxy will be listening.

To run the Proxy as a child process, which will be automatically terminated if the Application proccess stoped, add the following line to the config.ru file:

# config.ru – this file is used by Rack-based servers to start the application
require File.expand_path('../config/environment',  __FILE__)

ApolloTracing.start_proxy('config/apollo-engine-proxy.json')
# or pass a JSON string:
# ApolloTracing.start_proxy('{"apiKey": "KEY", ...}')

run Your::Application

For example, if you use rails with puma application server and run it like:

bundle exec puma -w 2 -t 16 -p 3000

The proccess tree may look like:

                ---------------
               |  Puma Master  |
               |   Port 3000   |
                ---------------
                   |      |
         ----------        ----------
        |                            |    ----------------
        ˅                             -> |  Puma Worker1  |
 ----------------                    |    -----------------
|  Engine Proxy  |                   |    ----------------
|   Port 3001    |                    -> |  Puma Worker2  |
 ----------------                         ----------------

Now you can send requests to the reverse Proxy http://localhost:3001. It'll proxy any (GraphQL and non-GraphQL) requests to the Application http://localhost:3000. If the request matches the endpoints described in origins, it'll strip the tracing data from the response and will send it to the Apollo Engine service.

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.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/uniiverse/apollo-tracing-ruby. 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.

apollo-tracing-ruby's People

Contributors

exaspark avatar glasser avatar lunks avatar olleolleolle avatar rsuh avatar seannguyen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

apollo-tracing-ruby's Issues

Usage on Heroku

Hello! Thanks so much for writing this gem.

The examples mention localhost and following them I got this set up for my local dev environment quite easily. However, I'm not sure what to use a config for when I've deployed the app (we're using Heroku). I'd be happy to write up and make a PR for the README for how to do this if you could point me in the right direction.

Thanks!

Maintainers Wanted

We are looking for people to help out and maintain the gem since our company no longer uses Apollo Engine.

Please comment on this issue if you're interested.

Heroku Set Up

Hi! Did someone have success using this in Heroku? If so, how did you do it?
I'm currently trying to send metrics to the Apollo Graph Manager but, I have not been able to perform that from Heroku, just locally.

Any help will be appreciated

Proxy crashes after multiple errors

I setup this gem for our production GraphQL API today and within an hour our API stopped responding and I saw this error in the logs from the proxy:

time="2018-06-27T17:42:25Z" 
level=warning 
msg="Received unsupported Content-Type from origin GraphQL server. This often occurs when a GraphQL server throws an error and sends that error as `text/plain` instead of embedding it within a GraphQL error. Check to make sure any errors encountered during resolver execution and middleware processing are translated into the GraphQL errors field. This could also be caused by an inaccurate Content-Type header." 
content-type=text/html 
response-body="{\"message\": \"Something went wrong. We've already been notified of the problem and are working to fix it. We apologise for the inconvenience.\"}"

That error repeated 15 times before I see this in the log
Couldn't cleanly terminate the Apollo Engine Proxy in 3 seconds!

After that point, the proxy completely died and all API requests went ignored.

So from the error message I'm wondering if I need to change the format of the 500.html page to be JSON instead of a text/html format and if that would fix the issue? Also I'm wondering why the proxy doesn't try to restart itself after dying.

Thanks in advance for the help!

Cody

Support for multiple HTTP origins

I have a use case where we have different schemas and endpoints within the same application. Specifically, we have a different GraphQL for each bounded context within our application.

However, when providing a configuration file with multiple HTTP origins, it will only take the last line in the configuration.

I believe that the proxy itself works this way, if an exact path match is found, it will forward to the last registered origin. Otherwise, it will simply proxy the request.

To illustrate, this is my configuration:

APOLLO_CONFIG = %Q(
{
  "apiKey": "#{ENV['APOLLO_API_KEY']}",
  "logging": { "level": "#{ENV['APOLLO_LOG_LEVEL']}" },
  "origins": [
    { "http": { "url": "http://#{ENV['HOST']}:#{ENV['PORT']}/api/endpoint_a/" } },
    { "http": { "url": "http://#{ENV['HOST']}:#{ENV['PORT']}/api/endpoint_b/" } }
  ],
  "frontends": [
    { "host": "#{ENV['APOLLO_PROXY_HOST']}", "port": #{ENV['APOLLO_PROXY_PORT']}, "endpoint": "/" }
  ]
}
).freeze

In this case, the frontend's endpoint is /, which will cause all the requests to proxy normally, but this is still a problem because then the tracing data is not stripped out.

If I provide one or more frontends that provide an exact match, like so:

{ "host": "#{ENV['APOLLO_PROXY_HOST']}", "port": #{ENV['APOLLO_PROXY_PORT']}, "endpoint": "/api/endpoint_a/" },
{ "host": "#{ENV['APOLLO_PROXY_HOST']}", "port": #{ENV['APOLLO_PROXY_PORT']}, "endpoint": "/api/endpoint_b/" }

Then as mentioned, only the last endpoint specific in origins is called.

What I would expect is that the proxy allows the configuration of multiple frontends and backends.

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.