@sentry/nextjs
Version:
Official Sentry SDK for Next.js
62 lines (55 loc) • 2.65 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
const core = require('@sentry/core');
const utils = require('@sentry/utils');
const debugBuild = require('../debug-build.js');
/**
* Wrap `res.end()` so that it closes the transaction and flushes events before letting the request finish.
*
* Note: This wraps a sync method with an async method. While in general that's not a great idea in terms of keeping
* things in the right order, in this case it's safe, because the native `.end()` actually *is* (effectively) async, and
* its run actually *is* (literally) awaited, just manually so (which reflects the fact that the core of the
* request/response code in Node by far predates the introduction of `async`/`await`). When `.end()` is done, it emits
* the `prefinish` event, and only once that fires does request processing continue. See
* https://github.com/nodejs/node/commit/7c9b607048f13741173d397795bac37707405ba7.
*
* Also note: `res.end()` isn't called until *after* all response data and headers have been sent, so blocking inside of
* `end` doesn't delay data getting to the end user. See
* https://nodejs.org/api/http.html#responseenddata-encoding-callback.
*
* @param transaction The transaction tracing request handling
* @param res: The request's corresponding response
*/
function autoEndTransactionOnResponseEnd(transaction, res) {
const wrapEndMethod = (origEnd) => {
return function sentryWrappedEnd( ...args) {
finishTransaction(transaction, this);
return origEnd.call(this, ...args);
};
};
// Prevent double-wrapping
// res.end may be undefined during build when using `next export` to statically export a Next.js app
if (res.end && !(res.end ).__sentry_original__) {
utils.fill(res, 'end', wrapEndMethod);
}
}
/** Finish the given response's transaction and set HTTP status data */
function finishTransaction(transaction, res) {
if (transaction) {
transaction.setHttpStatus(res.statusCode);
transaction.end();
}
}
/** Flush the event queue to ensure that events get sent to Sentry before the response is finished and the lambda ends */
async function flushQueue() {
try {
debugBuild.DEBUG_BUILD && utils.logger.log('Flushing events...');
await core.flush(2000);
debugBuild.DEBUG_BUILD && utils.logger.log('Done flushing events');
} catch (e) {
debugBuild.DEBUG_BUILD && utils.logger.log('Error while flushing events:\n', e);
}
}
exports.autoEndTransactionOnResponseEnd = autoEndTransactionOnResponseEnd;
exports.finishTransaction = finishTransaction;
exports.flushQueue = flushQueue;
//# sourceMappingURL=responseEnd.js.map