Skip to content

Commit

Permalink
fix(express): listen for finish event on response for async express…
Browse files Browse the repository at this point in the history
… layer #107
  • Loading branch information
vmarchaud committed Aug 29, 2020
1 parent 58cd219 commit 5ec7473
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
10 changes: 8 additions & 2 deletions plugins/node/opentelemetry-plugin-express/src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,15 @@ 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(() => {
/**
* As 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', () => {
if (spanHasEnded === false) {
spanHasEnded = true;
span.end(startTime);
}
});
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) => {
setTimeout(() => {
return res.status(200).end();
}, 5);
});
const server = http.createServer(app);
await new Promise(resolve => server.listen(0, resolve));
Expand Down

0 comments on commit 5ec7473

Please sign in to comment.