pax_global_header00006660000000000000000000000064140731331470014515gustar00rootroot0000000000000052 comment=a44ca1a3ebe5440211b0142f796760bb17aeee30 http-timer-4.0.6/000077500000000000000000000000001407313314700136215ustar00rootroot00000000000000http-timer-4.0.6/.editorconfig000066400000000000000000000002571407313314700163020ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 http-timer-4.0.6/.gitignore000066400000000000000000000000601407313314700156050ustar00rootroot00000000000000.nyc_output node_modules package-lock.json dist http-timer-4.0.6/.npmrc000066400000000000000000000000231407313314700147340ustar00rootroot00000000000000package-lock=false http-timer-4.0.6/.travis.yml000066400000000000000000000001271407313314700157320ustar00rootroot00000000000000language: node_js node_js: - '13' - '12' - '10' after_success: npm run coveralls http-timer-4.0.6/LICENSE000066400000000000000000000020571407313314700146320ustar00rootroot00000000000000MIT License Copyright (c) 2018 Szymon Marczak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. http-timer-4.0.6/README.md000066400000000000000000000056171407313314700151110ustar00rootroot00000000000000# http-timer > Timings for HTTP requests [![Build Status](https://travis-ci.org/szmarczak/http-timer.svg?branch=master)](https://travis-ci.org/szmarczak/http-timer) [![Coverage Status](https://coveralls.io/repos/github/szmarczak/http-timer/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/http-timer?branch=master) [![install size](https://packagephobia.now.sh/badge?p=@szmarczak/http-timer)](https://packagephobia.now.sh/result?p=@szmarczak/http-timer) Inspired by the [`request` package](https://github.com/request/request). ## Installation NPM: > `npm install @szmarczak/http-timer` Yarn: > `yarn add @szmarczak/http-timer` ## Usage **Note:** > - The measured events resemble Node.js events, not the kernel ones. > - Sending a chunk greater than [`highWaterMark`](https://nodejs.org/api/stream.html#stream_new_stream_writable_options) will result in invalid `upload` and `response` timings. You can avoid this by splitting the payload into smaller chunks. ```js const https = require('https'); const timer = require('@szmarczak/http-timer'); const request = https.get('https://httpbin.org/anything'); timer(request); request.once('response', response => { response.resume(); response.once('end', () => { console.log(response.timings); // You can use `request.timings` as well }); }); // { // start: 1572712180361, // socket: 1572712180362, // lookup: 1572712180415, // connect: 1572712180571, // upload: 1572712180884, // response: 1572712181037, // end: 1572712181039, // error: undefined, // abort: undefined, // phases: { // wait: 1, // dns: 53, // tcp: 156, // request: 313, // firstByte: 153, // download: 2, // total: 678 // } // } ``` ## API ### timer(request) Returns: `Object` **Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. - `start` - Time when the request started. - `socket` - Time when a socket was assigned to the request. - `lookup` - Time when the DNS lookup finished. - `connect` - Time when the socket successfully connected. - `secureConnect` - Time when the socket securely connected. - `upload` - Time when the request finished uploading. - `response` - Time when the request fired `response` event. - `end` - Time when the response fired `end` event. - `error` - Time when the request fired `error` event. - `abort` - Time when the request fired `abort` event. - `phases` - `wait` - `timings.socket - timings.start` - `dns` - `timings.lookup - timings.socket` - `tcp` - `timings.connect - timings.lookup` - `tls` - `timings.secureConnect - timings.connect` - `request` - `timings.upload - (timings.secureConnect || timings.connect)` - `firstByte` - `timings.response - timings.upload` - `download` - `timings.end - timings.response` - `total` - `(timings.end || timings.error || timings.abort) - timings.start` If something has not been measured yet, it will be `undefined`. ## License MIT http-timer-4.0.6/package.json000066400000000000000000000025511407313314700161120ustar00rootroot00000000000000{ "name": "@szmarczak/http-timer", "version": "4.0.6", "description": "Timings for HTTP requests", "main": "dist/source", "engines": { "node": ">=10" }, "scripts": { "test": "xo && tsc --noEmit && nyc ava", "build": "del-cli dist && tsc", "prepare": "npm run build", "coveralls": "nyc report --reporter=text-lcov | coveralls" }, "files": [ "dist/source" ], "keywords": [ "http", "https", "timer", "timings" ], "repository": { "type": "git", "url": "git+https://github.com/szmarczak/http-timer.git" }, "author": "Szymon Marczak", "license": "MIT", "bugs": { "url": "https://github.com/szmarczak/http-timer/issues" }, "homepage": "https://github.com/szmarczak/http-timer#readme", "dependencies": { "defer-to-connect": "^2.0.0" }, "devDependencies": { "@ava/typescript": "^2.0.0", "@sindresorhus/tsconfig": "^1.0.2", "@types/node": "^16.3.1", "ava": "^3.15.0", "coveralls": "^3.1.1", "del-cli": "^3.0.1", "http2-wrapper": "^2.0.7", "nyc": "^15.1.0", "p-event": "^4.2.0", "typescript": "^4.3.5", "xo": "^0.39.1" }, "types": "dist/source", "nyc": { "extension": [ ".ts" ], "exclude": [ "**/tests/**" ] }, "xo": { "rules": { "@typescript-eslint/no-non-null-assertion": "off" } }, "ava": { "typescript": { "compile": false, "rewritePaths": { "tests/": "dist/tests/" } } } } http-timer-4.0.6/source/000077500000000000000000000000001407313314700151215ustar00rootroot00000000000000http-timer-4.0.6/source/index.ts000066400000000000000000000106551407313314700166070ustar00rootroot00000000000000import {EventEmitter} from 'events'; import {Socket} from 'net'; import {ClientRequest, IncomingMessage} from 'http'; import deferToConnect from 'defer-to-connect'; import {types} from 'util'; export interface Timings { start: number; socket?: number; lookup?: number; connect?: number; secureConnect?: number; upload?: number; response?: number; end?: number; error?: number; abort?: number; phases: { wait?: number; dns?: number; tcp?: number; tls?: number; request?: number; firstByte?: number; download?: number; total?: number; }; } export interface ClientRequestWithTimings extends ClientRequest { timings?: Timings; } export interface IncomingMessageWithTimings extends IncomingMessage { timings?: Timings; } const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); const timer = (request: ClientRequestWithTimings): Timings => { if (request.timings) { return request.timings; } const timings: Timings = { start: Date.now(), socket: undefined, lookup: undefined, connect: undefined, secureConnect: undefined, upload: undefined, response: undefined, end: undefined, error: undefined, abort: undefined, phases: { wait: undefined, dns: undefined, tcp: undefined, tls: undefined, request: undefined, firstByte: undefined, download: undefined, total: undefined } }; request.timings = timings; const handleError = (origin: EventEmitter): void => { const emit = origin.emit.bind(origin); origin.emit = (event, ...args: unknown[]) => { // Catches the `error` event if (event === 'error') { timings.error = Date.now(); timings.phases.total = timings.error - timings.start; origin.emit = emit; } // Saves the original behavior return emit(event, ...args); }; }; handleError(request); const onAbort = (): void => { timings.abort = Date.now(); // Let the `end` response event be responsible for setting the total phase, // unless the Node.js major version is >= 13. if (!timings.response || nodejsMajorVersion >= 13) { timings.phases.total = Date.now() - timings.start; } }; request.prependOnceListener('abort', onAbort); const onSocket = (socket: Socket): void => { timings.socket = Date.now(); timings.phases.wait = timings.socket - timings.start; if (types.isProxy(socket)) { return; } const lookupListener = (): void => { timings.lookup = Date.now(); timings.phases.dns = timings.lookup - timings.socket!; }; socket.prependOnceListener('lookup', lookupListener); deferToConnect(socket, { connect: () => { timings.connect = Date.now(); if (timings.lookup === undefined) { socket.removeListener('lookup', lookupListener); timings.lookup = timings.connect; timings.phases.dns = timings.lookup - timings.socket!; } timings.phases.tcp = timings.connect - timings.lookup; // This callback is called before flushing any data, // so we don't need to set `timings.phases.request` here. }, secureConnect: () => { timings.secureConnect = Date.now(); timings.phases.tls = timings.secureConnect - timings.connect!; } }); }; if (request.socket) { onSocket(request.socket); } else { request.prependOnceListener('socket', onSocket); } const onUpload = (): void => { timings.upload = Date.now(); timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect!); }; const writableFinished = (): boolean => { if (typeof request.writableFinished === 'boolean') { return request.writableFinished; } // Node.js doesn't have `request.writableFinished` property return request.finished && (request as any).outputSize === 0 && (!request.socket || request.socket.writableLength === 0); }; if (writableFinished()) { onUpload(); } else { request.prependOnceListener('finish', onUpload); } request.prependOnceListener('response', (response: IncomingMessageWithTimings): void => { timings.response = Date.now(); timings.phases.firstByte = timings.response - timings.upload!; response.timings = timings; handleError(response); response.prependOnceListener('end', () => { timings.end = Date.now(); timings.phases.download = timings.end - timings.response!; timings.phases.total = timings.end - timings.start; }); response.prependOnceListener('aborted', onAbort); }); return timings; }; export default timer; // For CommonJS default export support module.exports = timer; module.exports.default = timer; http-timer-4.0.6/tests/000077500000000000000000000000001407313314700147635ustar00rootroot00000000000000http-timer-4.0.6/tests/test.ts000066400000000000000000000250531407313314700163170ustar00rootroot00000000000000import {EventEmitter} from 'events'; import http = require('http'); import {ClientRequest, IncomingMessage} from 'http'; import https = require('https'); import {AddressInfo} from 'net'; import util = require('util'); import pEvent from 'p-event'; import test from 'ava'; import timer, {Timings, ClientRequestWithTimings, IncomingMessageWithTimings} from '../source'; import http2 = require('http2-wrapper'); let server: http.Server & { url?: string; listenAsync?: any; closeAsync?: any; }; test.before('setup', async () => { server = http.createServer((_request, response) => { response.write('o'); setTimeout(() => { response.end('k'); }, 200); }); server.listenAsync = util.promisify(server.listen.bind(server)); server.closeAsync = util.promisify(server.close.bind(server)); await server.listenAsync(); server.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); test.after('cleanup', async () => { await server.closeAsync(); }); const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); const error = 'Simple error'; const makeRequest = (url = 'https://httpbin.org/anything', options: http.RequestOptions = {}): {request: ClientRequest; timings: Timings} => { const {protocol} = new URL(url); const fn = protocol === 'http:' ? http : https; const request = fn.get(url, {agent: false, ...options}); const timings = timer(request); return {request, timings}; }; test('by default everything is set to undefined', t => { const {timings} = makeRequest(); t.is(typeof timings, 'object'); t.is(typeof timings.start, 'number'); t.is(timings.socket, undefined); t.is(timings.lookup, undefined); t.is(timings.connect, undefined); t.is(timings.secureConnect, undefined); t.is(timings.response, undefined); t.is(timings.end, undefined); t.is(timings.error, undefined); t.is(timings.abort, undefined); t.deepEqual(timings.phases, { wait: undefined, dns: undefined, tcp: undefined, tls: undefined, request: undefined, firstByte: undefined, download: undefined, total: undefined }); }); test('timings (socket reuse)', async t => { const agent = new http.Agent({keepAlive: true}); { const {request} = makeRequest(server.url, {agent}); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); } { const {request} = makeRequest(server.url, {agent}); await pEvent(request, 'socket'); const timings = timer(request); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.true(timings.phases.wait! <= 1); t.true(timings.phases.dns! <= 1); t.true(timings.phases.tcp! <= 1); t.true(timings.phases.request! <= 1); } agent.destroy(); t.pass(); }); test('timings', async t => { const {request, timings} = makeRequest(); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.is(typeof timings, 'object'); t.is(typeof timings.start, 'number'); t.is(typeof timings.socket, 'number'); t.is(typeof timings.lookup, 'number'); t.is(typeof timings.connect, 'number'); t.is(typeof timings.secureConnect, 'number'); t.is(typeof timings.upload, 'number'); t.is(typeof timings.response, 'number'); t.is(typeof timings.end, 'number'); }); test('phases', async t => { const {request, timings} = makeRequest(); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.is(typeof timings.phases, 'object'); t.is(typeof timings.phases.wait, 'number'); t.is(typeof timings.phases.dns, 'number'); t.is(typeof timings.phases.tcp, 'number'); t.is(typeof timings.phases.tls, 'number'); t.is(typeof timings.phases.firstByte, 'number'); t.is(typeof timings.phases.download, 'number'); t.is(typeof timings.phases.total, 'number'); t.is(timings.phases.wait, timings.socket! - timings.start); t.is(timings.phases.dns, timings.lookup! - timings.socket!); t.is(timings.phases.tcp, timings.connect! - timings.lookup!); t.is(timings.phases.tls, timings.secureConnect! - timings.connect!); t.is(timings.phases.request, timings.upload! - timings.secureConnect!); t.is(timings.phases.firstByte, timings.response! - timings.upload!); t.is(timings.phases.download, timings.end! - timings.response!); t.is(timings.phases.total, timings.end! - timings.start); }); test('no memory leak (`lookup` event)', async t => { const {request} = makeRequest(); await pEvent(request, 'finish'); t.is(request.socket!.listenerCount('lookup'), 0); }); test('sets `total` on request error', async t => { const request = http.get(server.url!, { timeout: 1 }); request.on('timeout', () => { request.abort(); }); const timings = timer(request); const error: Error = await pEvent(request, 'error'); t.is(error.message, 'socket hang up'); t.is(typeof timings.error, 'number'); t.is(timings.phases.total, timings.error! - timings.start); }); test('sets `total` on response error', async t => { const request = http.get(server.url!, (response: IncomingMessage) => { setImmediate(() => { response.emit('error', new Error(error)); }); }); const timings = timer(request); const response: IncomingMessage = await pEvent(request, 'response'); const error_: Error = await pEvent(response, 'error'); t.is(error_.message, error); t.is(typeof timings.error, 'number'); t.is(timings.phases.total, timings.error! - timings.start); }); test.cb('sets `total` on abort', t => { const request = http.get(server.url!); request.abort(); const timings = timer(request); process.nextTick(() => { t.is(typeof timings.abort, 'number'); t.is(timings.phases.total, timings.abort! - timings.start); t.falsy((request as any).res); t.end(); }); }); test.cb('sets `total` on abort - after `response` event', t => { const request = http.get(server.url!); const timings = timer(request); request.once('response', response => { request.abort(); if (nodejsMajorVersion >= 13) { process.nextTick(() => { t.is(typeof timings.abort, 'number'); t.is(timings.phases.total, timings.abort! - timings.start); t.truthy((request as any).res); t.end(); }); } else { response.once('end', () => { t.is(typeof timings.abort, 'number'); t.is(timings.phases.total, timings.end! - timings.start); t.truthy((request as any).res); t.end(); }); } }); }); test('doesn\'t throw when someone used `.prependOnceListener()`', t => { const emitter = new EventEmitter(); timer(emitter as ClientRequest); // eslint-disable-next-line @typescript-eslint/no-empty-function emitter.prependOnceListener('error', () => {}); t.notThrows(() => emitter.emit('error', new Error(error))); }); test('sensible timings', async t => { const {timings, request} = makeRequest('https://google.com'); const now = Date.now(); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.true(timings.socket! >= now); t.true(timings.lookup! >= now); t.true(timings.connect! >= now); t.true(timings.secureConnect! >= now); t.true(timings.response! >= now); t.true(timings.end! >= now); t.is(timings.error, undefined); t.is(timings.abort, undefined); t.true(timings.phases.wait! < 1000); t.true(timings.phases.dns! < 1000); t.true(timings.phases.tcp! < 1000); t.true(timings.phases.tls! < 1000); t.true(timings.phases.request! < 1000); t.true(timings.phases.firstByte! < 1000); t.true(timings.phases.download! < 1000); t.true(timings.phases.total! < 1000); }); test('prepends once listeners', async t => { const request = https.get('https://google.com'); const promise = new Promise(resolve => { request.once('response', () => { t.true(typeof timings.response === 'number'); resolve(); }); const timings = timer(request); }); await promise; request.abort(); }); test('`tls` phase for https requests', async t => { const {request, timings} = makeRequest('https://google.com'); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.is(typeof timings.secureConnect, 'number'); t.is(typeof timings.phases.tls, 'number'); }); test('no `tls` phase for http requests', async t => { const {request, timings} = makeRequest(server.url); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); await pEvent(response, 'end'); t.is(timings.secureConnect, undefined); t.is(timings.phases.tls, undefined); }); test('timings are accessible via `request.timings`', t => { const {request, timings} = makeRequest('https://google.com'); request.abort(); const typedRequest = request as ClientRequestWithTimings; t.is(typedRequest.timings, timings); }); test('timings are accessible via `response.timings`', async t => { const {request, timings} = makeRequest('https://google.com'); const response: IncomingMessage = await pEvent(request, 'response'); const typedResponse = response as IncomingMessageWithTimings; t.is(typedResponse.timings, timings); response.resume(); await pEvent(response, 'end'); }); test('can extend `http.IncomingMessage`', t => { interface Response extends IncomingMessage { timings: boolean; } 0 as unknown as Response; t.pass(); }); test('singleton', t => { const {request, timings} = makeRequest('https://google.com'); request.abort(); const secondTimings = timer(request); const typedRequest = request as ClientRequestWithTimings; t.is(typedRequest.timings, timings); t.is(timings, secondTimings); }); test('sets `abort` on response.destroy()', async t => { const {request, timings} = makeRequest(server.url); const response = await pEvent(request, 'response'); response.destroy(); await pEvent(request, 'close'); t.is(typeof timings.abort, 'number'); }); const version = process.versions.node.split('.').map(v => Number(v)) as [number, number, number]; if (version[0] >= 16) { test('skips proxy-wrapped sockets', async t => { const request = await http2.auto('https://httpbin.org/anything'); const timings = timer(request); request.end(); const response: IncomingMessage = await pEvent(request, 'response'); response.resume(); t.is(request.socket!.listenerCount('lookup'), 0); await pEvent(response, 'end'); t.is(typeof timings, 'object'); t.is(typeof timings.start, 'number'); t.is(typeof timings.socket, 'number'); t.is(timings.lookup, undefined); t.is(timings.connect, undefined); t.is(timings.secureConnect, undefined); t.is(typeof timings.response, 'number'); t.is(typeof timings.end, 'number'); t.is(timings.error, undefined); t.is(timings.abort, undefined); }); } http-timer-4.0.6/tsconfig.json000066400000000000000000000013771407313314700163400ustar00rootroot00000000000000{ "compilerOptions": { // https://github.com/sindresorhus/tsconfig/blob/3f5f189a9b895e0d9da72078b574df7b917f5ec8/tsconfig.json "outDir": "dist", "target": "es2018", // Node.js 10 "module": "commonjs", "moduleResolution": "node", "resolveJsonModule": true, "jsx": "react", "declaration": true, "pretty": true, "newLine": "lf", "stripInternal": true, "strict": true, "noImplicitReturns": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedIndexedAccess": true, "noPropertyAccessFromIndexSignature": true, "noEmitOnError": true, "useDefineForClassFields": true, "forceConsistentCasingInFileNames": true, "skipLibCheck": true }, "include": [ "source", "tests" ] }