keepAlive.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Analyzes if HTTP responses keep the connections alive.
  3. */
  4. exports.version = '0.1';
  5. exports.module = function(phantomas) {
  6. 'use strict';
  7. phantomas.setMetric('closedConnections'); // @desc requests not keeping the connection alive and slowing down the next request @offenders
  8. var closedConnectionHosts = {};
  9. phantomas.on('recv', function(entry, res) {
  10. var connectionHeader = (entry.headers.Connection || '').toLowerCase();
  11. // Taking the protocol in account, in case the same domain is called with two different protocols.
  12. var host = entry.protocol + '://' + entry.domain;
  13. if (connectionHeader.indexOf('close') >= 0) {
  14. // Don't blame it immediatly, wait to see if the connection is needed a second time.
  15. closedConnectionHosts[host] = entry.url;
  16. }
  17. });
  18. phantomas.on('send', function(entry, res) {
  19. var host = entry.protocol + '://' + entry.domain;
  20. var previousClosedConnection = closedConnectionHosts[host];
  21. if (previousClosedConnection) {
  22. // There was a closed connection. We can blame it safely now!
  23. phantomas.incrMetric('closedConnections');
  24. phantomas.addOffender('closedConnections', previousClosedConnection);
  25. closedConnectionHosts[host] = null;
  26. }
  27. });
  28. };