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: Make it possible to get the active span in the GraphQL resolver #2323

Open
wants to merge 1 commit into
base: main
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
5 changes: 5 additions & 0 deletions .changeset/clever-rice-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@envelop/sentry': minor
---

Make it possible to get the active span in the GraphQL resolver
43 changes: 43 additions & 0 deletions packages/plugins/sentry/__tests__/sentry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useSentry } from '@envelop/sentry';
import { assertSingleExecutionValue, createTestkit } from '@envelop/testing';
import { makeExecutableSchema } from '@graphql-tools/schema';
import * as Sentry from '@sentry/node';
import { Span } from '@sentry/types';
import '@sentry/tracing';

describe('sentry', () => {
Expand Down Expand Up @@ -256,4 +257,46 @@ describe('sentry', () => {
name: 'Error',
});
});

test('get the active span', async () => {
const { testkit: sentryTestkit, sentryTransport } = createSentryTestkit();
Sentry.init({
dsn: 'https://[email protected]/1',
transport: sentryTransport,
});

let activeSpan: Span | undefined;
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String!
}
`,
resolvers: {
Query: {
hello: async () => {
activeSpan = Sentry.getActiveSpan();
return 'Hello!';
},
},
},
});

const envelopTestkit = createTestkit([useSentry()], schema);
const result = await envelopTestkit.execute('{ hello }');
expect(result).toMatchInlineSnapshot(`
{
"data": {
"hello": "Hello!",
},
}
`);
expect(activeSpan).not.toBeUndefined();

// run sentry flush
await new Promise(res => setTimeout(res, 10));

const reports = sentryTestkit.reports();
expect(reports).toHaveLength(0);
});
});
207 changes: 93 additions & 114 deletions packages/plugins/sentry/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { GraphQLError, Kind, OperationDefinitionNode, print } from 'graphql';
import {
ExecuteFunction,
ExecutionArgs,
ExecutionResult,
getDocumentString,
handleStreamOrSingleExecutionResult,
isOriginalGraphQLError,
OnExecuteDoneHookResultOnNextHook,
TypedExecutionArgs,
type Plugin,
} from '@envelop/core';
Expand Down Expand Up @@ -106,7 +107,7 @@ export const useSentry = <PluginContext extends Record<string, any> = {}>(
}

return {
onExecute({ args }) {
onExecute({ args, executeFn, setExecuteFn }) {
if (skipOperation(args)) {
return;
}
Expand All @@ -131,56 +132,93 @@ export const useSentry = <PluginContext extends Record<string, any> = {}>(
...addedTags,
};

let rootSpan: Span | undefined;
const createExecuteFn = async (
args: ExecutionArgs,
span: Span,
): Promise<ReturnType<ExecuteFunction>> => {
span.setAttribute('document', document);

if (startTransaction) {
Sentry.startSpan(
{
name: transactionName,
op,
attributes: tags,
...traceparentData,
},
span => {
rootSpan = span;
},
);
const result: ExecutionResult = await executeFn(args);

if (!rootSpan) {
const error = [
`Could not create the root Sentry transaction for the GraphQL operation "${transactionName}".`,
`It's very likely that this is because you have not included the Sentry tracing SDK in your app's runtime before handling the request.`,
];
throw new Error(error.join('\n'));
if (includeRawResult) {
// @ts-expect-error TODO: not sure if this is correct
span.setAttribute('result', result);
}
} else {
let childSpan: Span | undefined;
const scope = Sentry.getCurrentScope();
const parentSpan = scope?.getScopeData().span;
if (!parentSpan) {
// eslint-disable-next-line no-console
console.warn(
[
`Flag "startTransaction" is disabled but Sentry failed to find a transaction.`,
`Try to create a transaction before GraphQL execution phase is started.`,
].join('\n'),
);
return {};

if (result.errors && result.errors.length > 0) {
Sentry.withScope(scope => {
scope.setTransactionName(opName);
scope.setTag('operation', operationType);
scope.setTag('operationName', opName);
scope.setExtra('document', document);

scope.setTags(addedTags || {});

if (includeRawResult) {
scope.setExtra('result', result);
}

if (includeExecuteVariables) {
scope.setExtra('variables', args.variableValues);
}

const errors = result.errors?.map(err => {
if (skipError(err) === true) {
return err;
}

const errorPath = (err.path ?? [])
.map((v: string | number) => (typeof v === 'number' ? '$index' : v))
.join(' > ');

if (errorPath) {
scope.addBreadcrumb({
category: 'execution-path',
message: errorPath,
level: 'debug',
});
}

const eventId = Sentry.captureException(err.originalError, {
fingerprint: ['graphql', errorPath, opName, operationType],
contexts: {
GraphQL: {
operationName: opName,
operationType,
variables: args.variableValues,
},
},
});

return addEventId(err, eventId);
});

return {
...result,
errors,
};
});
}
Sentry.withActiveSpan(parentSpan, () => {

return result;
};

if (startTransaction) {
const executeFn: ExecuteFunction = args =>
Sentry.startSpan(
{
name: transactionName,
op,
attributes: tags,
...traceparentData,
},
span => {
childSpan = span;
},
span => createExecuteFn(args, span),
);
});

if (!childSpan) {
setExecuteFn(executeFn);
} else {
const scope = Sentry.getCurrentScope();
const parentSpan = scope?.getScopeData().span;
if (!parentSpan) {
// eslint-disable-next-line no-console
console.warn(
[
Expand All @@ -190,88 +228,29 @@ export const useSentry = <PluginContext extends Record<string, any> = {}>(
);
return {};
}

rootSpan = childSpan;
const executeFn: ExecuteFunction = args =>
Sentry.withActiveSpan(parentSpan, () => {
return Sentry.startSpan(
{
name: transactionName,
op,
attributes: tags,
},
span => createExecuteFn(args, span),
);
});
setExecuteFn(executeFn);

if (renameTransaction) {
scope!.setTransactionName(transactionName);
}
}

rootSpan.setAttribute('document', document);

if (options.configureScope) {
options.configureScope(args, Sentry.getCurrentScope());
}

return {
onExecuteDone(payload) {
const handleResult: OnExecuteDoneHookResultOnNextHook<{}> = ({ result, setResult }) => {
if (includeRawResult) {
// @ts-expect-error TODO: not sure if this is correct
rootSpan?.setAttribute('result', result);
}

if (result.errors && result.errors.length > 0) {
Sentry.withScope(scope => {
scope.setTransactionName(opName);
scope.setTag('operation', operationType);
scope.setTag('operationName', opName);
scope.setExtra('document', document);

scope.setTags(addedTags || {});

if (includeRawResult) {
scope.setExtra('result', result);
}

if (includeExecuteVariables) {
scope.setExtra('variables', args.variableValues);
}

const errors = result.errors?.map(err => {
if (skipError(err) === true) {
return err;
}

const errorPath = (err.path ?? [])
.map((v: string | number) => (typeof v === 'number' ? '$index' : v))
.join(' > ');

if (errorPath) {
scope.addBreadcrumb({
category: 'execution-path',
message: errorPath,
level: 'debug',
});
}

const eventId = Sentry.captureException(err.originalError, {
fingerprint: ['graphql', errorPath, opName, operationType],
contexts: {
GraphQL: {
operationName: opName,
operationType,
variables: args.variableValues,
},
},
});

return addEventId(err, eventId);
});

setResult({
...result,
errors,
});
});
}

rootSpan?.end();
};
return handleStreamOrSingleExecutionResult(payload, handleResult);
},
};
return {};
},
};
};