Skip to content
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

fix(express): listen for finish event on response for async express layer #107 #188

Merged
merged 4 commits into from
Sep 30, 2020
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
23 changes: 16 additions & 7 deletions plugins/node/opentelemetry-plugin-express/src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,22 @@ export class ExpressPlugin extends BasePlugin<typeof express> {
span.end(startTime);
spanHasEnded = true;
}
// listener for response.on('finish')
const onResponseFinish = () => {
if (spanHasEnded === false) {
spanHasEnded = true;
span.end(startTime);
}
};
// verify we have a callback
const args = Array.from(arguments);
const callbackIdx = args.findIndex(arg => typeof arg === 'function');
if (callbackIdx >= 0) {
arguments[callbackIdx] = function () {
if (spanHasEnded === false) {
span.end();
spanHasEnded = true;
req.res?.removeListener('finish', onResponseFinish);
span.end();
}
if (!(req.route && arguments[0] instanceof Error)) {
(req[_LAYERS_STORE_PROPERTY] as string[]).pop();
Expand All @@ -218,12 +226,13 @@ export class ExpressPlugin extends BasePlugin<typeof express> {
};
}
const result = original.apply(this, arguments);
// If the callback is never called, we need to close the span.
setImmediate(() => {
if (spanHasEnded === false) {
span.end(startTime);
}
});
/**
* At this point if the callback wasn't called, that means either the
* layer is asynchronous (so it will call the callback later on) or that
* the layer directly end the http response, so we'll hook into the "finish"
* event to handle the later case.
*/
req.res?.once('finish', onResponseFinish);
return result;
};
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ describe('Express Plugin', () => {
});
const router = express.Router();
app.use('/toto', router);
router.get('/:id', (req, res, next) => {
return res.status(200).end();
router.get('/:id', (req, res) => {
setImmediate(() => {
res.status(200).end();
});
});
const server = http.createServer(app);
await new Promise(resolve => server.listen(0, resolve));
Expand Down