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 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
21 changes: 19 additions & 2 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ Sentry.getGlobalScope().addEventProcessor(event => {

The `lastEventId` function has been removed. See [below](./MIGRATION.md#deprecate-lasteventid) for more details.

#### Remove `void` from transport return types
#### Removal of `void` from transport return types

The `send` method on the `Transport` interface now always requires a `TransportMakeRequestResponse` to be returned in
the promise. This means that the `void` return type is no longer allowed.
Expand All @@ -590,7 +590,7 @@ interface Transport {
}
```

#### Remove `addGlobalEventProcessor` in favor of `addEventProcessor`
#### Removal of `addGlobalEventProcessor` in favor of `addEventProcessor`

In v8, we are removing the `addGlobalEventProcessor` function in favor of `addEventProcessor`.

Expand All @@ -610,6 +610,23 @@ addEventProcessor(event => {
});
```

#### Removal of `Sentry.Handlers.trpcMiddleware()` in favor of `Sentry.trpcMiddleware()`

The Sentry tRPC middleware got moved from `Sentry.Handlers.trpcMiddleware()` to `Sentry.trpcMiddleware()`. Functionally
they are the same:

```js
// v7
import * as Sentry from '@sentry/node';
Sentry.Handlers.trpcMiddleware();
```

```js
// v8
import * as Sentry from '@sentry/node';
Sentry.trpcMiddleware();
```

### Browser SDK (Browser, React, Vue, Angular, Ember, etc.)

Removed top-level exports: `Offline`, `makeXHRTransport`, `BrowserTracing`, `wrap`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ for (const dependent of dependentsToCheck) {
}

if (Object.keys(missingExports).length > 0) {
console.error('\n❌ Found missing exports from @sentry/node in the following packages:\n');
console.log('\n❌ Found missing exports from @sentry/node in the following packages:\n');
console.log(JSON.stringify(missingExports, null, 2));
process.exit(1);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
"test:assert": "pnpm test"
},
"dependencies": {
"@sentry/core": "latest || *",
"@sentry/node": "latest || *",
"@sentry/types": "latest || *",
"express": "4.19.2",
"@trpc/server": "10.45.2",
"@trpc/client": "10.45.2",
"@types/express": "4.17.17",
"@types/node": "18.15.1",
"typescript": "4.9.5"
"express": "4.19.2",
"typescript": "4.9.5",
"zod": "^3.22.4"
},
"devDependencies": {
"@playwright/test": "^1.27.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import * as Sentry from '@sentry/node';
import { TRPCError, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import express from 'express';
import { z } from 'zod';

declare global {
namespace globalThis {
Expand Down Expand Up @@ -94,3 +97,36 @@ Sentry.addEventProcessor(event => {

return event;
});

export const t = initTRPC.context<Context>().create();

const procedure = t.procedure.use(Sentry.trpcMiddleware({ attachRpcInput: true }));

export const appRouter = t.router({
getSomething: procedure.input(z.string()).query(opts => {
return { id: opts.input, name: 'Bilbo' };
}),
createSomething: procedure.mutation(async () => {
await new Promise(resolve => setTimeout(resolve, 400));
return { success: true };
}),
crashSomething: procedure.mutation(() => {
throw new Error('I crashed in a trpc handler');
}),
dontFindSomething: procedure.mutation(() => {
throw new TRPCError({ code: 'NOT_FOUND', cause: new Error('Page not found') });
}),
});

export type AppRouter = typeof appRouter;

const createContext = () => ({ someStaticValue: 'asdf' });
type Context = Awaited<ReturnType<typeof createContext>>;

app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
}),
);
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { expect, test } from '@playwright/test';
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import axios, { AxiosError, AxiosResponse } from 'axios';
import { waitForError } from '../event-proxy-server';
import { waitForError, waitForTransaction } from '../event-proxy-server';
import type { AppRouter } from '../src/app';

const authToken = process.env.E2E_TEST_AUTH_TOKEN;
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG;
Expand Down Expand Up @@ -130,3 +132,96 @@ test('Should record uncaught exceptions with local variable', async ({ baseURL }

expect(frames[frames.length - 1].vars?.randomVariableToRecord).toBeDefined();
});

test('Should record transaction for trpc query', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('node-express-app', transactionEvent => {
return transactionEvent.transaction === 'trpc/getSomething';
});

const trpcClient = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${baseURL}/trpc`,
}),
],
});

await trpcClient.getSomething.query('foobar');

await expect(transactionEventPromise).resolves.toBeDefined();
const transaction = await transactionEventPromise;

expect(transaction.contexts?.trpc).toMatchObject({
procedure_type: 'query',
input: 'foobar',
});
});

test('Should record transaction for trpc mutation', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('node-express-app', transactionEvent => {
return transactionEvent.transaction === 'trpc/createSomething';
});

const trpcClient = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${baseURL}/trpc`,
}),
],
});

await trpcClient.createSomething.mutate();

await expect(transactionEventPromise).resolves.toBeDefined();
const transaction = await transactionEventPromise;

expect(transaction.contexts?.trpc).toMatchObject({
procedure_type: 'mutation',
});
});

test('Should record transaction and error for a crashing trpc handler', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('node-express-app', transactionEvent => {
return transactionEvent.transaction === 'trpc/crashSomething';
});

const errorEventPromise = waitForError('node-express-app', errorEvent => {
return !!errorEvent?.exception?.values?.some(exception => exception.value?.includes('I crashed in a trpc handler'));
});

const trpcClient = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${baseURL}/trpc`,
}),
],
});

await expect(trpcClient.crashSomething.mutate()).rejects.toBeDefined();

await expect(transactionEventPromise).resolves.toBeDefined();
await expect(errorEventPromise).resolves.toBeDefined();
});

test('Should record transaction and error for a trpc handler that returns a status code', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('node-express-app', transactionEvent => {
return transactionEvent.transaction === 'trpc/dontFindSomething';
});

const errorEventPromise = waitForError('node-express-app', errorEvent => {
return !!errorEvent?.exception?.values?.some(exception => exception.value?.includes('Page not found'));
});

const trpcClient = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${baseURL}/trpc`,
}),
],
});

await expect(trpcClient.dontFindSomething.mutate()).rejects.toBeDefined();

await expect(transactionEventPromise).resolves.toBeDefined();
await expect(errorEventPromise).resolves.toBeDefined();
});
1 change: 1 addition & 0 deletions packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export {
spotlightIntegration,
initOpenTelemetry,
spanToJSON,
trpcMiddleware,
} from '@sentry/node';

export {
Expand Down
1 change: 1 addition & 0 deletions packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export {
spotlightIntegration,
initOpenTelemetry,
spanToJSON,
trpcMiddleware,
} from '@sentry/node';

export {
Expand Down
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>(opts: SentryTrpcMiddlewareArguments<T>): T {
const { path, type, next, rawInput } = opts;
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);
span.end();
throw e;
}

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/google-cloud-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export {
spotlightIntegration,
initOpenTelemetry,
spanToJSON,
trpcMiddleware,
} from '@sentry/node';

export {
Expand Down
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