Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: base opentelemetry integration #363

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const {
MER_ERR_METHOD_NOT_ALLOWED,
MER_ERR_INVALID_METHOD
} = require('./lib/errors')
const tracer = require('./lib/tracer')

const kLoaders = Symbol('mercurius.loaders')
const kFactory = Symbol('mercurius.loadersFactory')
Expand Down Expand Up @@ -382,12 +383,18 @@ const plugin = fp(async function (app, opts) {
}

async function fastifyGraphQl (source, context, variables, operationName) {
const span = tracer.startSpan('mercurius - graphql', { parent: tracer.getCurrentSpan() })

context = Object.assign({ app: this, lruGatewayResolvers }, context)
const reply = context.reply

// Parse, with a little lru
const cached = lru !== null && lru.get(source)
let document = null

// Add opentelemetry attributes
span.setAttribute('mercurius.cached', !!cached)

if (!cached) {
// We use two caches to avoid errors bust the good
// cache. This is a protection against DoS attacks
Expand All @@ -397,6 +404,7 @@ const plugin = fp(async function (app, opts) {
// this query errored
const err = new MER_ERR_GQL_VALIDATION()
err.errors = cachedError.validationErrors
span.end()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually on erros error info is added to span as status code

const { SpanStatusCode } = require('@opentelemetry/api')

span.setStatus({
  code: SpanStatusCode.ERROR,
  message: error.message,
});

As well as OK status on success.

span.setStatus({
  code: SpanStatusCode.OK,
});

Also to avoid multiple span.end() I prefer following pattern:

const result = tracer.startActiveSpan(
  `<span_name>`,
  { attributes: <spanAttributes> },
  async (span) => {
    try {
      // do something
      span.setStatus({ code: SpanStatusCode.OK });
      // return if needed
    } catch (error) {
      span.setStatus({
        code: SpanStatusCode.ERROR,
        message: error.message,
      });
      throw error;
    } finally {
      span.end();
    }
  },
);
return result;

But it might be little bit less performant. And this one is available in most recent opentelemetry API, not sure about version from package.json.

throw err
}

Expand All @@ -405,6 +413,7 @@ const plugin = fp(async function (app, opts) {
} catch (syntaxError) {
const err = new MER_ERR_GQL_VALIDATION()
err.errors = [syntaxError]
span.end()
throw err
}

Expand All @@ -425,6 +434,7 @@ const plugin = fp(async function (app, opts) {
}
const err = new MER_ERR_GQL_VALIDATION()
err.errors = validationErrors
span.end()
throw err
}

Expand All @@ -434,6 +444,7 @@ const plugin = fp(async function (app, opts) {
if (queryDepthErrors.length > 0) {
const err = new MER_ERR_GQL_VALIDATION()
err.errors = queryDepthErrors
span.end()
throw err
}
}
Expand All @@ -451,6 +462,7 @@ const plugin = fp(async function (app, opts) {
if (operationAST.operation !== 'query') {
const err = new MER_ERR_METHOD_NOT_ALLOWED()
err.errors = [new Error('Operation cannot be performed via a GET request')]
span.end()
throw err
}
}
Expand All @@ -463,7 +475,9 @@ const plugin = fp(async function (app, opts) {
if (cached && cached.jit !== null) {
const execution = await cached.jit.query(root, context, variables || {})

return maybeFormatErrors(execution, context)
const resWithFormatedErrors = maybeFormatErrors(execution, context)
span.end()
return resWithFormatedErrors
}

// Validate variables
Expand All @@ -472,6 +486,7 @@ const plugin = fp(async function (app, opts) {
if (Array.isArray(executionContext)) {
const err = new MER_ERR_GQL_VALIDATION()
err.errors = executionContext
span.end()
throw err
}
}
Expand All @@ -485,7 +500,9 @@ const plugin = fp(async function (app, opts) {
operationName
)

return maybeFormatErrors(execution, context)
const resWithFormatedErrors = maybeFormatErrors(execution, context)
span.end()
return resWithFormatedErrors
}

function maybeFormatErrors (execution, context) {
Expand Down
5 changes: 5 additions & 0 deletions lib/tracer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict'
const api = require('@opentelemetry/api')
const meta = require('../package.json')

module.exports = api.trace.getTracer(meta.name, meta.version)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@graphql-tools/merge": "^6.2.4",
"@graphql-tools/schema": "^6.2.4",
"@graphql-tools/utils": "^6.2.4",
"@opentelemetry/api": "^0.13.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@opentelemetry/api version 0.16.0 changes the API significantly, if we do want to get this in we should try to build against the most up to date tracer API and active-context-getting functions they have available (the getSpan, setSpan stuff)

"@sinonjs/fake-timers": "^6.0.1",
"@types/node": "^14.0.23",
"@types/ws": "^7.2.6",
Expand Down
75 changes: 75 additions & 0 deletions test/opentelemetry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const api = require('@opentelemetry/api')
const GQL = require('..')

test('Should add opentelemetry span and cached attribute', async (t) => {
t.plan(6)

const testSpanContext = {
traceId: 'd4cda95b652f4a1592b449d5929fda1b',
spanId: '6e0c63257de34c92',
traceFlags: api.TraceFlags.NONE
}
class TestSpan extends api.NoopSpan {
setAttribute (name, value) {
t.is(name, 'mercurius.cached')
t.is(value, false)
}

end () {
t.pass()
}
}
const dummySpan = new TestSpan(testSpanContext)
class TestTracer extends api.NoopTracer {
startSpan (name, opts) {
t.is(name, 'mercurius - graphql')
t.deepEquals(opts.parent.context(), dummySpan.context())
return new TestSpan()
}

getCurrentSpan () {
return dummySpan
}
}
class TestTracerProvider extends api.NoopTracerProvider {
getTracer () {
return new TestTracer()
}
}
api.trace.setGlobalTracerProvider(new TestTracerProvider())

const app = Fastify()
const schema = `
type Query {
add(x: Int, y: Int): Int
}
`

const resolvers = {
add: async ({ x, y }) => x + y
}

app.register(GQL, {
schema,
resolvers
})

app.get('/', async function (req, reply) {
const query = '{ add(x: 2, y: 2) }'
return reply.graphql(query)
})

const res = await app.inject({
method: 'GET',
url: '/'
})

t.deepEqual(JSON.parse(res.body), {
data: {
add: 4
}
})
})