@envelop/sentry
Version:
This plugin collects errors and performance tracing for your execution flow, and reports it to [Sentry](https://sentry.io).
158 lines (157 loc) • 7.78 kB
JavaScript
import { Kind, print } from 'graphql';
import { getDocumentString, handleStreamOrSingleExecutionResult, isOriginalGraphQLError, } from '@envelop/core';
import * as Sentry from '@sentry/node';
export const defaultSkipError = isOriginalGraphQLError;
export const useSentry = (options = {}) => {
function pick(key, defaultValue) {
return options[key] ?? defaultValue;
}
const startTransaction = pick('startTransaction', true);
const includeRawResult = pick('includeRawResult', false);
const includeExecuteVariables = pick('includeExecuteVariables', false);
const renameTransaction = pick('renameTransaction', false);
const skipOperation = pick('skip', () => false);
const skipError = pick('skipError', defaultSkipError);
const eventIdKey = options.eventIdKey === null ? null : 'sentryEventId';
function addEventId(err, eventId) {
if (eventIdKey !== null && eventId !== null) {
err.extensions[eventIdKey] = eventId;
}
return err;
}
return {
onExecute({ args }) {
if (skipOperation(args)) {
return;
}
const rootOperation = args.document.definitions.find(
// @ts-expect-error TODO: not sure how we will make it dev friendly
o => o.kind === Kind.OPERATION_DEFINITION);
const operationType = rootOperation.operation;
const document = getDocumentString(args.document, print);
const opName = args.operationName || rootOperation.name?.value || 'Anonymous Operation';
const addedTags = (options.appendTags && options.appendTags(args)) || {};
const traceparentData = (options.traceparentData && options.traceparentData(args)) || {};
const transactionName = options.transactionName ? options.transactionName(args) : opName;
const op = options.operationName ? options.operationName(args) : 'execute';
const tags = {
operationName: opName,
operation: operationType,
...addedTags,
};
let rootSpan;
if (startTransaction) {
Sentry.startSpan({
name: transactionName,
op,
attributes: tags,
...traceparentData,
}, span => {
rootSpan = span;
});
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'));
}
}
else {
let childSpan;
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 {};
}
Sentry.withActiveSpan(parentSpan, () => {
Sentry.startSpan({
name: transactionName,
op,
attributes: tags,
}, span => {
childSpan = span;
});
});
if (!childSpan) {
// 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 {};
}
rootSpan = childSpan;
if (renameTransaction) {
scope.setTransactionName(transactionName);
}
}
rootSpan.setAttribute('document', document);
if (options.configureScope) {
options.configureScope(args, Sentry.getCurrentScope());
}
return {
onExecuteDone(payload) {
const handleResult = ({ 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) => (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);
},
};
},
};
};