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

experiment: [plugin/sentry] Use OTEL plugin for Sentry #2334

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
8 changes: 8 additions & 0 deletions .changeset/@envelop_sentry-2334-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@envelop/sentry": patch
---
dependencies updates:
- Added dependency [`@envelop/opentelemetry@workspace:^` ↗︎](https://www.npmjs.com/package/@envelop/opentelemetry/v/workspace:^) (to `dependencies`)
- Added dependency [`@opentelemetry/api@^1.8.0` ↗︎](https://www.npmjs.com/package/@opentelemetry/api/v/1.8.0) (to `dependencies`)
- Added dependency [`@opentelemetry/sdk-trace-base@^1.11.0` ↗︎](https://www.npmjs.com/package/@opentelemetry/sdk-trace-base/v/1.11.0) (to `dependencies`)
- Added dependency [`@sentry/opentelemetry@^8.40.0` ↗︎](https://www.npmjs.com/package/@sentry/opentelemetry/v/8.40.0) (to `dependencies`)
5 changes: 5 additions & 0 deletions .changeset/popular-bears-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@envelop/sentry': major
---

Use OpenTelemetry instead of Sentry SDK
1 change: 1 addition & 0 deletions packages/plugins/sentry/__tests__/sentry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe('sentry', () => {
Sentry.init({
dsn: 'https://[email protected]/1',
transport: sentryTransport,
skipOpenTelemetrySetup: true,
});

const schema = makeExecutableSchema({
Expand Down
6 changes: 5 additions & 1 deletion packages/plugins/sentry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,18 @@
"graphql": "^14.0.0 || ^15.0.0 || ^16.0.0"
},
"dependencies": {
"@envelop/opentelemetry": "workspace:^",
"@opentelemetry/api": "^1.8.0",
"@opentelemetry/sdk-trace-base": "^1.11.0",
"@sentry/opentelemetry": "^8.40.0",
"tslib": "^2.5.0"
},
"devDependencies": {
"@envelop/core": "workspace:^",
"@graphql-tools/schema": "10.0.8",
"@sentry/node": "^8.22.0",
"@sentry/tracing": "^7.114.0",
"@sentry/types": "^8.22.0",
"@sentry/types": "^8.32.0",
"graphql": "16.8.1",
"sentry-testkit": "5.0.9",
"typescript": "5.1.3"
Expand Down
318 changes: 52 additions & 266 deletions packages/plugins/sentry/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,277 +1,63 @@
import { GraphQLError, Kind, OperationDefinitionNode, print } from 'graphql';
import {
getDocumentString,
handleStreamOrSingleExecutionResult,
isOriginalGraphQLError,
OnExecuteDoneHookResultOnNextHook,
TypedExecutionArgs,
type Plugin,
} from '@envelop/core';
import { type Plugin } from '@envelop/core';
import { useOpenTelemetry, type TracingOptions } from '@envelop/opentelemetry';
import { Attributes, SpanKind, TracerProvider } from '@opentelemetry/api';
import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';
import * as Sentry from '@sentry/node';
import type { Span, TraceparentData } from '@sentry/types';

export type SentryPluginOptions<PluginContext extends Record<string, any>> = {
/**
* Starts a new transaction for every GraphQL Operation.
* When disabled, an already existing Transaction will be used.
*
* @default true
*/
startTransaction?: boolean;
/**
* Renames Transaction.
* @default false
*/
renameTransaction?: boolean;
/**
* Adds result of each resolver and operation to Span's data (available under "result")
* @default false
*/
includeRawResult?: boolean;
/**
* Adds operation's variables to a Scope (only in case of errors)
* @default false
*/
includeExecuteVariables?: boolean;
/**
* The key of the event id in the error's extension. `null` to disable.
* @default sentryEventId
*/
eventIdKey?: string | null;
/**
* Adds custom tags to every Transaction.
*/
appendTags?: (args: TypedExecutionArgs<PluginContext>) => Record<string, unknown>;
/**
* Callback to set context information onto the scope.
*/
configureScope?: (args: TypedExecutionArgs<PluginContext>, scope: Sentry.Scope) => void;
/**
* Produces a name of Transaction (only when "renameTransaction" or "startTransaction" are enabled) and description of created Span.
*
* @default operation's name or "Anonymous Operation" when missing)
*/
transactionName?: (args: TypedExecutionArgs<PluginContext>) => string;
/**
* Produces tracing data for Transaction
*
* @default is empty
*/
traceparentData?: (args: TypedExecutionArgs<PluginContext>) => TraceparentData | undefined;
/**
* Produces a "op" (operation) of created Span.
*
* @default execute
*/
operationName?: (args: TypedExecutionArgs<PluginContext>) => string;
/**
* Indicates whether or not to skip the entire Sentry flow for given GraphQL operation.
* By default, no operations are skipped.
*/
skip?: (args: TypedExecutionArgs<PluginContext>) => boolean;
/**
* Indicates whether or not to skip Sentry exception reporting for a given error.
* By default, this plugin skips all `GraphQLError` errors and does not report it to Sentry.
*/
skipError?: (args: Error) => boolean;
import { SentryPropagator, SentrySampler, SentrySpanProcessor } from '@sentry/opentelemetry';
import type { Client } from '@sentry/types';

export type SentryPluginOptions = {
otel?: TracingOptions;
tracingProvider?: TracerProvider;
spanKind?: SpanKind;
spanAdditionalAttributes?: Attributes;
serviceName?: string;
spanPrefix?: string;
};

export const defaultSkipError = isOriginalGraphQLError;

export const useSentry = <PluginContext extends Record<string, any> = {}>(
options: SentryPluginOptions<PluginContext> = {},
): Plugin<PluginContext> => {
function pick<K extends keyof SentryPluginOptions<PluginContext>>(
key: K,
defaultValue: NonNullable<SentryPluginOptions<PluginContext>[K]>,
) {
return options[key] ?? defaultValue;
export const useSentry = <PluginContext extends Record<string, any> = {}>({
otel = {},
tracingProvider,
spanKind,
spanAdditionalAttributes,
serviceName,
spanPrefix,
}: SentryPluginOptions = {}): Plugin<PluginContext> => {
const client = Sentry.getClient();
if (!client) {
throw new Error(
"Sentry is not initialized. This plugin doesn't initialize Sentry automatically" +
'Please call `Sentry.init` as describe in Sentry documentation',
);
}

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: GraphQLError, eventId: string | null): GraphQLError {
if (eventIdKey !== null && eventId !== null) {
err.extensions[eventIdKey] = eventId;
}

return err;
if (!tracingProvider) {
const provider = new BasicTracerProvider({
sampler: new SentrySampler(client as Client),
});
provider.addSpanProcessor(new SentrySpanProcessor());
provider.register({
propagator: new SentryPropagator(),
contextManager: new Sentry.SentryContextManager(),
});

Sentry.validateOpenTelemetrySetup();
tracingProvider = provider;
}

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,
) as OperationDefinitionNode;
const operationType = rootOperation.operation;

const document = getDocumentString(args.document, print);

const opName = args.operationName || rootOperation.name?.value || 'Anonymous Operation';
const addedTags: Record<string, any> = (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: Span | undefined;

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: 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 {};
}
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: 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);
},
};
onPluginInit({ addPlugin }) {
addPlugin(
// @ts-expect-error TODO: fix types
useOpenTelemetry(
otel ?? {},
tracingProvider,
spanKind,
spanAdditionalAttributes,
serviceName,
spanPrefix,
),
);
},
};
};
Loading
Loading