Skip to content

feat(node): Add Fastify integration #9138

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

Closed
wants to merge 2 commits into from
Closed
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
45 changes: 45 additions & 0 deletions packages/node-experimental/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,51 @@ All of these are auto-discovered, you don't need to configure anything for perfo
You still need to register middlewares etc. for error capturing.
Other, non-performance integrations from `@sentry/node` are also available (except for Undici).

## Fully supported Frameworks

### Express

```js
const Sentry = require('@sentry/node-experimental');

Sentry.init({
dsn: '...',
tracesSampleRate: 1,
});

// Ensure `init` was called _before_ you require express!
const express = require('express');
const app = express();

// Add your routes

// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());

app.listen(3000);
```

### Fastify

```js
const Sentry = require('@sentry/node-experimental');

Sentry.init({
dsn: '...',
tracesSampleRate: 1,
});

// Ensure `init` was called _before_ you require fastify!
const fastify = require('fastify');
const app = fastify();

app.register(Sentry.fastifyErrorPlugin());

// Add your routes

app.listen();
```

## Links

- [Official SDK Docs](https://docs.sentry.io/quickstart/)
1 change: 1 addition & 0 deletions packages/node-experimental/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export {
trace,
withScope,
captureCheckIn,
fastifyErrorPlugin,
} from '@sentry/node';

export type {
Expand Down
5 changes: 3 additions & 2 deletions packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@types/lru-cache": "^5.1.0",
"@types/node": "~10.17.0",
"express": "^4.17.1",
"fastify": "^4.23.2",
"nock": "^13.0.5",
"undici": "^5.21.0"
},
Expand All @@ -61,8 +62,8 @@
"lint": "run-s lint:prettier lint:eslint",
"lint:eslint": "eslint . --format stylish",
"lint:prettier": "prettier --check \"{src,test,scripts}/**/**.ts\"",
"test": "run-s test:jest test:express test:webpack test:release-health",
"test:express": "node test/manual/express-scope-separation/start.js",
"test": "run-s test:jest test:integration test:webpack test:release-health",
"test:integration": "node test/manual/integration/runner.js",
"test:jest": "jest",
"test:release-health": "node test/manual/release-health/runner.js",
"test:webpack": "cd test/manual/webpack-async-context/ && yarn --silent && node npm-build.js",
Expand Down
6 changes: 2 additions & 4 deletions packages/node/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,10 @@ export function requestHandler(
const client = currentHub.getClient<NodeClient>();
if (isAutoSessionTrackingEnabled(client)) {
setImmediate(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (client && (client as any)._captureRequestSession) {
if (client && client['_captureRequestSession']) {
// Calling _captureRequestSession to capture request session at the end of the request by incrementing
// the correct SessionAggregates bucket i.e. crashed, errored or exited
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(client as any)._captureRequestSession();
client['_captureRequestSession']();
}
});
}
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 @@ -87,3 +87,4 @@ const INTEGRATIONS = {
};

export { INTEGRATIONS as Integrations, Handlers };
export { fastifyErrorPlugin } from './integrations/fastify';
146 changes: 146 additions & 0 deletions packages/node/src/integrations/fastify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { captureException, getCurrentHub, runWithAsyncContext } from '@sentry/core';
import type { Integration } from '@sentry/types';
import { logger } from '@sentry/utils';
import type * as http from 'http';

import type { NodeClient } from '../client';
import { isAutoSessionTrackingEnabled } from '../sdk';

// We do not want to have fastify as a dependency, so we mock the type here

type FastifyPlugin = (fastify: FastifyInstance, _options: unknown, pluginDone: () => void) => void;

type RequestHookHandler = (
this: FastifyInstance,
request: http.IncomingMessage,
reply: unknown,
done: () => void,
) => void;
interface FastifyInstance {
register: (plugin: FastifyPlugin) => void;

/**
* `onRequest` is the first hook to be executed in the request lifecycle. There was no previous hook, the next hook will be `preParsing`.
* Notice: in the `onRequest` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.
*/
/**
* `onResponse` is the seventh and last hook in the request hook lifecycle. The previous hook was `onSend`, there is no next hook.
* The onResponse hook is executed when a response has been sent, so you will not be able to send more data to the client. It can however be useful for sending data to external services, for example to gather statistics.
*/
addHook(name: 'onRequest' | 'onResponse', hook: RequestHookHandler): void;

/**
* This hook is useful if you need to do some custom error logging or add some specific header in case of error.
* It is not intended for changing the error, and calling reply.send will throw an exception.
* This hook will be executed only after the customErrorHandler has been executed, and only if the customErrorHandler sends an error back to the user (Note that the default customErrorHandler always sends the error back to the user).
* Notice: unlike the other hooks, pass an error to the done function is not supported.
*/
addHook(
name: 'onError',
hook: (
this: FastifyInstance,
request: http.IncomingMessage,
reply: unknown,
error: Error,
done: () => void,
) => void,
): void;
}

const SKIP_OVERRIDE = Symbol.for('skip-override');
const FASTIFY_DISPLAY_NAME = Symbol.for('fastify.display-name');

interface FastifyOptions {
fastify: FastifyInstance;
}

const fastifyRequestPlugin = (): FastifyPlugin =>
Object.assign(
(fastify: FastifyInstance, _options: unknown, pluginDone: () => void) => {
fastify.addHook('onRequest', (request, _reply, done) => {
runWithAsyncContext(() => {
const currentHub = getCurrentHub();
currentHub.configureScope(scope => {
scope.setSDKProcessingMetadata({
request,
});

const client = currentHub.getClient<NodeClient>();
if (isAutoSessionTrackingEnabled(client)) {
const scope = currentHub.getScope();
// Set `status` of `RequestSession` to Ok, at the beginning of the request
scope.setRequestSession({ status: 'ok' });
}
});

done();
});
});

fastify.addHook('onResponse', (_request, _reply, done) => {
const client = getCurrentHub().getClient<NodeClient>();
if (isAutoSessionTrackingEnabled(client)) {
setImmediate(() => {
if (client && client['_captureRequestSession']) {
// Calling _captureRequestSession to capture request session at the end of the request by incrementing
// the correct SessionAggregates bucket i.e. crashed, errored or exited
client['_captureRequestSession']();
}
});
}

done();
});

pluginDone();
},
{
[SKIP_OVERRIDE]: true,
[FASTIFY_DISPLAY_NAME]: 'SentryFastifyRequestPlugin',
},
);

export const fastifyErrorPlugin = (): FastifyPlugin =>
Object.assign(
(fastify: FastifyInstance, _options: unknown, pluginDone: () => void) => {
fastify.addHook('onError', (_request, _reply, error, done) => {
captureException(error);
done();
});

pluginDone();
},
{
[SKIP_OVERRIDE]: true,
[FASTIFY_DISPLAY_NAME]: 'SentryFastifyErrorPlugin',
},
);

/** Capture errors for your fastify app. */
export class Fastify implements Integration {
public static id: string = 'Fastify';
public name: string = Fastify.id;

private _fastify?: FastifyInstance;

public constructor(options?: FastifyOptions) {
const fastify = options?.fastify;
this._fastify = fastify && typeof fastify.register === 'function' ? fastify : undefined;

if (__DEBUG_BUILD__ && !this._fastify) {
logger.warn('The Fastify integration expects a fastify instance to be passed. No errors will be captured.');
}
}

/**
* @inheritDoc
*/
public setupOnce(): void {
if (!this._fastify) {
return;
}

void this._fastify.register(fastifyErrorPlugin());
void this._fastify.register(fastifyRequestPlugin());
}
}
1 change: 1 addition & 0 deletions packages/node/src/integrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export { Context } from './context';
export { RequestData } from './requestdata';
export { LocalVariables } from './localvariables';
export { Undici } from './undici';
export { Fastify } from './fastify';
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const http = require('http');
const express = require('express');
const app = express();
const Sentry = require('../../../build/cjs');
const { colorize } = require('../colorize');
const Sentry = require('../../../../build/cjs');
const { colorize } = require('../../colorize');
const { TextEncoder } = require('util');

// don't log the test errors we're going to throw, so at a quick glance it doesn't look like the test itself has failed
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const http = require('http');
const fastify = require('fastify');
const app = fastify();
const Sentry = require('../../../../build/cjs');
const { colorize } = require('../../colorize');
const { TextEncoder } = require('util');

// don't log the test errors we're going to throw, so at a quick glance it doesn't look like the test itself has failed
global.console.error = () => null;

function assertTags(actual, expected) {
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
console.log(colorize('FAILED: Scope contains incorrect tags\n', 'red'));
console.log(colorize(`Got: ${JSON.stringify(actual)}\n`, 'red'));
console.log(colorize(`Expected: ${JSON.stringify(expected)}\n`, 'red'));
process.exit(1);
}
}

let remaining = 3;

function makeDummyTransport() {
return Sentry.createTransport({ recordDroppedEvent: () => undefined, textEncoder: new TextEncoder() }, req => {
--remaining;

if (!remaining) {
console.log(colorize('PASSED: All scopes contain correct tags\n', 'green'));
app.close();
process.exit(0);
}

return Promise.resolve({
statusCode: 200,
});
});
}

Sentry.init({
dsn: 'http://[email protected]/1337',
transport: makeDummyTransport,
integrations: [new Sentry.Integrations.Fastify({ fastify: app })],
beforeSend(event) {
if (event.transaction === 'GET /foo') {
assertTags(event.tags, {
global: 'wat',
foo: 'wat',
});
} else if (event.transaction === 'GET /bar') {
assertTags(event.tags, {
global: 'wat',
bar: 'wat',
});
} else if (event.transaction === 'GET /baz') {
assertTags(event.tags, {
global: 'wat',
baz: 'wat',
});
} else {
assertTags(event.tags, {
global: 'wat',
});
}

return event;
},
});

Sentry.configureScope(scope => {
scope.setTag('global', 'wat');
});

app.get('/foo', req => {
Sentry.configureScope(scope => {
scope.setTag('foo', 'wat');
});

throw new Error('foo');
});

app.get('/bar', req => {
Sentry.configureScope(scope => {
scope.setTag('bar', 'wat');
});

throw new Error('bar');
});

app.get('/baz', async req => {
Sentry.configureScope(scope => {
scope.setTag('baz', 'wat');
});

await new Promise(resolve => setTimeout(resolve, 10));
Copy link
Contributor

Choose a reason for hiding this comment

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

require('node:timers/promises').setTimeout exist. We don't need to await new Promise here. Although, it might not work with Node 8.


throw new Error('baz');
});

app.listen({ port: 0 }, (err, address) => {
http.get(`${address}/foo`);
http.get(`${address}/bar`);
http.get(`${address}/baz`);
});
Loading