Skip to content

feat(node): Fork isolation scope in tRPC middleware #16296

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 1 commit into from
May 15, 2025
Merged
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
4 changes: 2 additions & 2 deletions packages/core/src/trpc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getClient, withScope } from './currentScopes';
import { getClient, withIsolationScope } from './currentScopes';
import { captureException } from './exports';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from './semanticAttributes';
import { startSpanManual } from './tracing';
Expand Down Expand Up @@ -76,7 +76,7 @@ export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
}
}

return withScope(scope => {
return withIsolationScope(scope => {
scope.setContext('trpc', trpcContext);
Copy link
Member

Choose a reason for hiding this comment

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

Should we have a check for something like so?

getIsolationScope() !== getDefaultIsolationScope()

so that we only use an isolation scope if it hasn't been explicitly set? This way we don't break server-use cases, like using trpcMiddleware in your express app.

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 this should be fine even on express. Middleware only runs on the server. What are your concerns?

Copy link
Member

Choose a reason for hiding this comment

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

I'm just worried we rebind a new isolation scope which interferes with a framework integration.

Like if you use the trpc middleware in a cloudflare worker: https://trpc.io/docs/server/adapters/fetch#create-cloudflare-worker

import * as Sentry from "@sentry/cloudflare";
import { initTRPC } from '@trpc/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { createContext } from './context';

const t = initTRPC.context().create();
const sentryMiddleware = t.middleware(
  Sentry.trpcMiddleware({
    attachRpcInput: true,
  }),
);
const sentrifiedProcedure = t.procedure.use(sentryMiddleware);
export const appRouter = t.router({
  getUserById: sentrifiedProcedure.input(...),
});

export default Sentry.withSentry(() => {}, {
  async fetch(request: Request): Promise<Response> {
    return fetchRequestHandler({
      endpoint: '/trpc',
      req: request,
      router: appRouter,
      createContext,
    });
  },
});

withSentry creates an isolation scope around fetch, but so would the getUserById trpc procedure. In this use case, we can just rely on the isolation scope from the fetch handler instrumentation.

Copy link
Member Author

Choose a reason for hiding this comment

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

The problem with this is that the isolation scope is already different from the default isolation scope, but the scope remains the same between the two middleware invocations which is why we end up with issue like tags "leaking".

return startSpanManual(
{
Expand Down
4 changes: 2 additions & 2 deletions packages/core/test/lib/trpc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('trpcMiddleware', () => {
setExtra: vi.fn(),
};

const withScope = vi.fn(callback => {
const withIsolationScope = vi.fn(callback => {
return callback(mockScope);
});

Expand All @@ -38,7 +38,7 @@ describe('trpcMiddleware', () => {
client.init();
vi.spyOn(currentScopes, 'getClient').mockReturnValue(mockClient);
vi.spyOn(tracing, 'startSpanManual').mockImplementation((name, callback) => callback(mockSpan, () => {}));
vi.spyOn(currentScopes, 'withScope').mockImplementation(withScope);
vi.spyOn(currentScopes, 'withIsolationScope').mockImplementation(withIsolationScope);
vi.spyOn(exports, 'captureException').mockImplementation(() => 'mock-event-id');
});

Expand Down
Loading