0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/lib/internal/http.js
vmarchaud 0ebf01dc53
perf_hooks: add HttpRequest statistics monitoring #28445
```js
const { PerformanceObserver, performance } = require('perf_hooks');
const http = require('http');

const obs = new PerformanceObserver((items) => {
  const entry = items.getEntries()[0];
  console.log(entry.name, entry.duration);
});
obs.observe({ entryTypes: ['http'] });

const server = http.Server(function(req, res) {
  server.close();
  res.writeHead(200);
  res.end('hello world\n');
});

server.listen(0, function() {
  const req = http.request({
    port: this.address().port,
    path: '/',
    method: 'POST'
  }).end();
});
```

PR-URL: https://github.com/nodejs/node/pull/28486
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
2019-07-12 00:36:27 +02:00

58 lines
1.2 KiB
JavaScript

'use strict';
const { setUnrefTimeout } = require('internal/timers');
const { PerformanceEntry, notify } = internalBinding('performance');
var nowCache;
var utcCache;
function nowDate() {
if (!nowCache) cache();
return nowCache;
}
function utcDate() {
if (!utcCache) cache();
return utcCache;
}
function cache() {
const d = new Date();
nowCache = d.valueOf();
utcCache = d.toUTCString();
setUnrefTimeout(resetCache, 1000 - d.getMilliseconds());
}
function resetCache() {
nowCache = undefined;
utcCache = undefined;
}
function ondrain() {
if (this._httpMessage) this._httpMessage.emit('drain');
}
class HttpRequestTiming extends PerformanceEntry {
constructor(statistics) {
super();
this.name = 'HttpRequest';
this.entryType = 'http';
const startTime = statistics.startTime;
const diff = process.hrtime(startTime);
this.duration = diff[0] * 1000 + diff[1] / 1e6;
this.startTime = startTime[0] * 1000 + startTime[1] / 1e6;
}
}
function emitStatistics(statistics) {
notify('http', new HttpRequestTiming(statistics));
}
module.exports = {
outHeadersKey: Symbol('outHeadersKey'),
ondrain,
nowDate,
utcDate,
emitStatistics
};