Skip to content

feat: Add trpcMiddleware back to serverside SDKs #11374

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

Merged
merged 5 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,4 @@ export { metricsDefault } from './metrics/exports-default';
export { BrowserMetricsAggregator } from './metrics/browser-aggregator';
export { getMetricSummaryJsonForSpan } from './metrics/metric-summary';
export { addTracingHeadersToFetchRequest, instrumentFetchRequest } from './fetch';
export { trpcMiddleware } from './trpc';
98 changes: 98 additions & 0 deletions packages/core/src/trpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { isThenable, normalize } from '@sentry/utils';
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
captureException,
setContext,
startSpanManual,
} from '.';
import { getClient } from './currentScopes';

interface SentryTrpcMiddlewareOptions {
/** Whether to include procedure inputs in reported events. Defaults to `false`. */
attachRpcInput?: boolean;
}

export interface SentryTrpcMiddlewareArguments<T> {
path?: unknown;
type?: unknown;
next: () => T;
rawInput?: unknown;
}

const trpcCaptureContext = { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } };

/**
* Sentry tRPC middleware that captures errors and creates spans for tRPC procedures.
*/
export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
return function <T>({ path, type, next, rawInput }: SentryTrpcMiddlewareArguments<T>): T {
const client = getClient();
const clientOptions = client && client.getOptions();

const trpcContext: Record<string, unknown> = {
procedure_type: type,
};

if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions && clientOptions.sendDefaultPii) {
trpcContext.input = normalize(rawInput);
}

setContext('trpc', trpcContext);

function captureIfError(nextResult: unknown): void {
// TODO: Set span status based on what TRPCError was encountered
if (
typeof nextResult === 'object' &&
nextResult !== null &&
'ok' in nextResult &&
!nextResult.ok &&
'error' in nextResult
) {
captureException(nextResult.error, trpcCaptureContext);
}
}

return startSpanManual(
{
name: `trpc/${path}`,
op: 'rpc.server',
forceTransaction: true,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.rpc.trpc',
},
},
span => {
let maybePromiseResult;
Copy link
Member

Choose a reason for hiding this comment

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

l: can we rewrite this to use handleCallbackErrors?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It will very much not reduce the code here by much, if at all, because we need to inspect maybePromiseResult.

try {
maybePromiseResult = next();
} catch (e) {
captureException(e, trpcCaptureContext);
throw e;
} finally {
span.end();
}

if (isThenable(maybePromiseResult)) {
return maybePromiseResult.then(
nextResult => {
captureIfError(nextResult);
span.end();
return nextResult;
},
e => {
captureException(e, trpcCaptureContext);
span.end();
throw e;
},
) as T;
} else {
captureIfError(maybePromiseResult);
span.end();
return maybePromiseResult;
}
},
);
};
}
1 change: 1 addition & 0 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export {
withActiveSpan,
getRootSpan,
spanToJSON,
trpcMiddleware,
} from '@sentry/core';

export type {
Expand Down
1 change: 1 addition & 0 deletions packages/remix/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export {
setupHapiErrorHandler,
spotlightIntegration,
setupFastifyErrorHandler,
trpcMiddleware,
} from '@sentry/node';

// Keeping the `*` exports for backwards compatibility and types
Expand Down
1 change: 1 addition & 0 deletions packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
trpcMiddleware,
} from '@sentry/node';

// We can still leave this for the carrier init and type exports
Expand Down
1 change: 1 addition & 0 deletions packages/vercel-edge/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
trpcMiddleware,
} from '@sentry/core';

export { VercelEdgeClient } from './client';
Expand Down