Skip to content

feat(node): Add Sentry tRPC middleware #7511

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 9 commits into from
Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ const INTEGRATIONS = {

export { INTEGRATIONS as Integrations, Handlers };

export { sentryTrpcMiddleware } from './trpc';
Copy link
Contributor

Choose a reason for hiding this comment

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

Not sure if lib-specific code should be exported directly from our core node package tbh. And if so, we can maybe put it under handlers.ts, where our express-related code lives already?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wouldn't know where else to put it. I think it is fine here, considering we also have stuff like specific DB integrations exported from the node pkg. Do you know a better place?

Also, I wouldn't put it into handlers. It's not really a handler lol. Also, I don't think it matters too much in which file we put it. I just wanted to be able to find it quickly if I fuzzy search for "trpc".

Copy link
Contributor

Choose a reason for hiding this comment

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

I think it is fine here, considering we also have stuff like specific DB integrations exported from the node pkg.

We don't, it's exported from tracing package :P

It's not really a handler lol.

Neither are express request and tracing "middlewares" that we call handlers, yet we expose them via Handlers :P

wdyt @AbhiPrasad? If we leave it here, I'd simplify the name to tRPCMiddleware as import 'sentrySomething' from 'sentry' sounds strange.

Copy link
Member

Choose a reason for hiding this comment

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

We don't, it's exported from tracing package :P

This will change, we want to rm -rf the tracing package. #7346

I'd simplify the name to tRPCMiddleware as import 'sentrySomething' from 'sentry' sounds strange.

Sounds fine to me. Only concern we might have is that it might collide with other packages, which might be annoying for vscode autocomplete (not a huge deal, but still some DX we need to think about).


// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like
// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.
const carrier = getMainCarrier();
Expand Down
44 changes: 44 additions & 0 deletions packages/node/src/trpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { getCurrentHub } from '@sentry/core';
import { normalize } from '@sentry/utils';

interface SentryTrpcMiddlewareOptions {
attachRpcInput?: boolean;
}

interface TrpcMiddlewareArguments<T> {
path: string;
type: 'query' | 'mutation' | 'subscription';
next: () => T;
rawInput: unknown;
}

/**
* Sentry tRPC middleware that names the handling transaction after the called procedure.
*
* Use the Sentry tRPC middleware in combination with the Sentry server integration,
* e.g. Express Request Handlers or Next.js SDK.
*/
export async function sentryTrpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
return function <T>({ path, type, next, rawInput }: TrpcMiddlewareArguments<T>): T {
const hub = getCurrentHub();
const clientOptions = hub.getClient()?.getOptions();
const sentryTransaction = hub.getScope()?.getTransaction();

if (sentryTransaction) {
sentryTransaction.setName(`${path}()`, 'route');
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this standardized format for RPC? We use urls directly as route value in other places, sometimes prepended with a METHOD.

Copy link
Contributor

Choose a reason for hiding this comment

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

I just use the path without added () when logging myself

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I asked the team if we have precedence or a convention around transaction names for RPCs. I believe it comes down to preference of how you would like it to look in the product.

Here, for tRPC at least, imo it doesn't make too much sense to show the METHOD in the transaction name since it is always POST anyways (correct me if I am wrong ^^) and it would just be noise. The method name is still included in the span details if the server is properly instrumented otherwise.

Considering the point about noise above, I think we should drop the (). It just makes the transaction name more lengthy without any real value. I believe I added it at first because it denoted quite well that something was a method call.

Copy link
Member

Choose a reason for hiding this comment

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

We should match OpenTelemetry here, which names their spans as: $package.$service/$method.

We do this already in our OpenTelemetry transformations across the different SDKs.

sentryTransaction.op = 'rpc.server';
Copy link
Contributor

Choose a reason for hiding this comment

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

https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/rpc.md I don't see rpc.server operation in the spec we follow, there's rpc only. Do we make a distinction here ourselves?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In general, I think it is fine to append stuff to the span op. I think there is a hierarchy to it. The docs are just a guide to set the baseline ops we should use.

Here I decided to append .server because we could at some point decide that we would like to instrument the client side part of RPCs and there we would probably call it rpc.client. Similar to how we do it with http.server and http.client.

Copy link
Member

Choose a reason for hiding this comment

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

Yeah this is fine, we can update our span operations spec to account for this https://develop.sentry.dev/sdk/performance/span-operations/


const trpcData: Record<string, unknown> = {
procedureType: type,
};

if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions?.sendDefaultPii) {
Copy link
Contributor

Choose a reason for hiding this comment

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

This might be somewhat confusing to users. sendDefaultPii is documented as something that controls headers and cookies, not the user-provided input.
I'd probably change it to options.attachRpcInput and add default to options: SentryTrpcMiddlewareOptions = {}, which is not currently set as optional anyway.

Copy link
Contributor Author

@lforst lforst Mar 20, 2023

Choose a reason for hiding this comment

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

sendDefaultPii has become much broader lately. We have a few places where we send additional data if sendDefaultPii is set to true, asides from just cookies and header. The docs just state cookies and headers as an example.

You're right about the optional options object. Thanks! --> 4d16e63

trpcData.procedureInput = normalize(rawInput);
}

sentryTransaction.setData('trpc', trpcData);
}

return next();
Copy link
Contributor

Choose a reason for hiding this comment

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

You might want to log something if the procedure actually fails? https://trpc.io/docs/server/middlewares#logging

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point, but for now I don't think we need to add this. People will still need to use this integration with a proper server framework integration like the Express integration for it to work, and those integrations will handle the errors.

We could at some point add an option that allows capturing of non-200 responses.

};
}