-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -51,6 +51,7 @@ export { | |
trace, | ||
withScope, | ||
captureCheckIn, | ||
fastifyErrorPlugin, | ||
} from '@sentry/node'; | ||
|
||
export type { | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletions
4
.../manual/express-scope-separation/start.js → ...ation/express/express-scope-separation.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
packages/node/test/manual/integration/fastify/fastify-scope-separation.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
|
||
throw new Error('baz'); | ||
}); | ||
|
||
app.listen({ port: 0 }, (err, address) => { | ||
http.get(`${address}/foo`); | ||
http.get(`${address}/bar`); | ||
http.get(`${address}/baz`); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.