-
Notifications
You must be signed in to change notification settings - Fork 16
/
app.js
161 lines (144 loc) · 4.46 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
'use strict'
const assert = require('assert')
const url = require('url')
const http = require('http')
const https = require('https')
const TIMEOUT_IN_MILLISECONDS = 30 * 1000
const NS_PER_SEC = 1e9
const MS_PER_NS = 1e6
/**
* Creates a request and collects HTTP timings
* @function request
* @param {Object} options
* @param {String} [options.method='GET']
* @param {String} options.protocol
* @param {String} options.hostname
* @param {Number} [options.port]
* @param {String} [options.path]
* @param {Object} [options.headers={}]
* @param {String} [options.body]
* @param {Function} callback
*/
function request ({
method = 'GET',
protocol,
hostname,
port,
path,
headers = {},
body
} = {}, callback) {
// Validation
assert(protocol, 'options.protocol is required')
assert(['http:', 'https:'].includes(protocol), 'options.protocol must be one of: "http:", "https:"')
assert(hostname, 'options.hostname is required')
assert(callback, 'callback is required')
// Initialization
const eventTimes = {
// use process.hrtime() as it's not a subject of clock drift
startAt: process.hrtime(),
dnsLookupAt: undefined,
tcpConnectionAt: undefined,
tlsHandshakeAt: undefined,
firstByteAt: undefined,
endAt: undefined
}
// Making request
const req = (protocol.startsWith('https') ? https : http).request({
protocol,
method,
hostname,
port,
path,
headers
}, (res) => {
let responseBody = ''
req.setTimeout(TIMEOUT_IN_MILLISECONDS)
// Response events
res.once('readable', () => {
eventTimes.firstByteAt = process.hrtime()
})
res.on('data', (chunk) => { responseBody += chunk })
// End event is not emitted when stream is not consumed fully
// in our case we consume it see: res.on('data')
res.on('end', () => {
eventTimes.endAt = process.hrtime()
callback(null, {
headers: res.headers,
timings: getTimings(eventTimes),
body: responseBody
})
})
})
// Request events
req.on('socket', (socket) => {
socket.on('lookup', () => {
eventTimes.dnsLookupAt = process.hrtime()
})
socket.on('connect', () => {
eventTimes.tcpConnectionAt = process.hrtime()
})
socket.on('secureConnect', () => {
eventTimes.tlsHandshakeAt = process.hrtime()
})
socket.on('timeout', () => {
req.abort()
const err = new Error('ETIMEDOUT')
err.code = 'ETIMEDOUT'
callback(err)
})
})
req.on('error', callback)
// Sending body
if (body) {
req.write(body)
}
req.end()
}
/**
* Calculates HTTP timings
* @function getTimings
* @param {Object} eventTimes
* @param {Number} eventTimes.startAt
* @param {Number|undefined} eventTimes.dnsLookupAt
* @param {Number} eventTimes.tcpConnectionAt
* @param {Number|undefined} eventTimes.tlsHandshakeAt
* @param {Number} eventTimes.firstByteAt
* @param {Number} eventTimes.endAt
* @return {Object} timings - { dnsLookup, tcpConnection, tlsHandshake, firstByte, contentTransfer, total }
*/
function getTimings (eventTimes) {
return {
// There is no DNS lookup with IP address
dnsLookup: eventTimes.dnsLookupAt !== undefined ?
getHrTimeDurationInMs(eventTimes.startAt, eventTimes.dnsLookupAt) : undefined,
tcpConnection: getHrTimeDurationInMs(eventTimes.dnsLookupAt || eventTimes.startAt, eventTimes.tcpConnectionAt),
// There is no TLS handshake without https
tlsHandshake: eventTimes.tlsHandshakeAt !== undefined ?
(getHrTimeDurationInMs(eventTimes.tcpConnectionAt, eventTimes.tlsHandshakeAt)) : undefined,
firstByte: getHrTimeDurationInMs((eventTimes.tlsHandshakeAt || eventTimes.tcpConnectionAt), eventTimes.firstByteAt),
contentTransfer: getHrTimeDurationInMs(eventTimes.firstByteAt, eventTimes.endAt),
total: getHrTimeDurationInMs(eventTimes.startAt, eventTimes.endAt)
}
}
/**
* Get duration in milliseconds from process.hrtime()
* @function getHrTimeDurationInMs
* @param {Array} startTime - [seconds, nanoseconds]
* @param {Array} endTime - [seconds, nanoseconds]
* @return {Number} durationInMs
*/
function getHrTimeDurationInMs (startTime, endTime) {
const secondDiff = endTime[0] - startTime[0]
const nanoSecondDiff = endTime[1] - startTime[1]
const diffInNanoSecond = secondDiff * NS_PER_SEC + nanoSecondDiff
return diffInNanoSecond / MS_PER_NS
}
// Getting timings
request(Object.assign(url.parse('https://api.github.com'), {
headers: {
'User-Agent': 'Example'
}
}), (err, res) => {
console.log(err || res.timings)
})