meta.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * meta middleware, should be the first middleware
  3. */
  4. 'use strict';
  5. const { performance } = require('perf_hooks');
  6. const semver = require('semver');
  7. module.exports = options => {
  8. // Node.js >=14.8.0 and >= 12.19.0 will set Keep-Alive Header, see https://github.com/nodejs/node/pull/34561
  9. const shouldPatchKeepAliveHeader = !semver.satisfies(process.version, '>=14.8.0 || ^12.19.0');
  10. return async function meta(ctx, next) {
  11. if (options.logging) {
  12. ctx.coreLogger.info('[meta] request started, host: %s, user-agent: %s', ctx.host, ctx.header['user-agent']);
  13. }
  14. await next();
  15. // total response time header
  16. if (ctx.performanceStarttime) {
  17. ctx.set('x-readtime', Math.floor((performance.now() - ctx.performanceStarttime) * 1000) / 1000);
  18. } else {
  19. ctx.set('x-readtime', Date.now() - ctx.starttime);
  20. }
  21. // try to support Keep-Alive Header when < 14.8.0
  22. const server = ctx.app.server;
  23. if (shouldPatchKeepAliveHeader && server && server.keepAliveTimeout && server.keepAliveTimeout >= 1000 && ctx.header.connection !== 'close') {
  24. /**
  25. * use Math.floor instead of parseInt. More: https://github.com/eggjs/egg/pull/2702
  26. */
  27. const timeout = Math.floor(server.keepAliveTimeout / 1000);
  28. ctx.set('keep-alive', `timeout=${timeout}`);
  29. }
  30. };
  31. };