forked from cypress-io/cypress
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_performance_spec.js
More file actions
428 lines (348 loc) · 11.4 KB
/
proxy_performance_spec.js
File metadata and controls
428 lines (348 loc) · 11.4 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
require('../spec_helper')
const { makeDataContext, setCtx, getCtx } = require('../../lib/makeDataContext')
setCtx(makeDataContext({}))
const cp = require('child_process')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const _ = require('lodash')
const { expect } = require('chai')
const debug = require('debug')('test:proxy-performance')
const DebuggingProxy = require('@cypress/debugging-proxy')
const HarCapturer = require('chrome-har-capturer')
const performance = require('@tooling/system-tests/lib/performance')
const Promise = require('bluebird')
const sanitizeFilename = require('sanitize-filename')
const { createRoutes } = require(`../../lib/routes`)
process.env.CYPRESS_INTERNAL_ENV = 'development'
const CA = require('@packages/https-proxy').CA
const { setupFullConfigWithDefaults } = require('@packages/config')
const { ServerBase } = require('../../lib/server-base')
const { SocketE2E } = require('../../lib/socket-e2e')
const { _getArgs } = require('../../lib/browsers/chrome')
const CHROME_PATH = 'google-chrome'
const URLS_UNDER_TEST = [
'https://test-page-speed.cypress.io/index1000.html',
'http://test-page-speed.cypress.io/index1000.html',
]
const start = (new Date()) / 1000
const PROXY_PORT = process.env.PROXY_PORT || 45678
const HTTPS_PROXY_PORT = process.env.HTTPS_PROXY_PORT || 45681
const CDP_PORT = 45679 /** port range starts here, not the actual port */
const CY_PROXY_PORT = 45680
const TEST_CASES = [
// these first 4 cases don't involve Cypress, don't need to run every time
// {
// name: 'Chrome w/o HTTP/2',
// disableHttp2: true,
// },
// {
// name: 'Chrome',
// },
// {
// name: 'With proxy',
// upstreamProxy: true,
// },
// {
// name: 'With HTTPS proxy',
// httpsUpstreamProxy: true,
// },
// baseline test that all other tests are compared to
{
name: 'Chrome w/ proxy w/o HTTP/2 (baseline)',
disableHttp2: true,
upstreamProxy: true,
},
{
name: 'With Cypress proxy, Intercepted',
cyProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy, Not Intercepted',
cyProxy: true,
},
{
name: 'With Cypress proxy w/o HTTP/2, Not Intercepted',
cyProxy: true,
disableHttp2: true,
},
{
name: 'With Cypress proxy and upstream, Intercepted',
cyProxy: true,
upstreamProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy and HTTPS upstream, Intercepted',
cyProxy: true,
httpsUpstreamProxy: true,
cyIntercept: true,
},
{
name: 'With Cypress proxy and upstream, Not Intercepted',
cyProxy: true,
upstreamProxy: true,
},
{
name: 'With Cypress proxy and HTTPS upstream, Not Intercepted',
cyProxy: true,
httpsUpstreamProxy: true,
},
].map((v) => {
// fill in all the fields so the keys are in the correct order for readability
return _.defaults(v, {
disableHttp2: false,
upstreamProxy: false,
httpsUpstreamProxy: false,
cyProxy: false,
cyIntercept: false,
})
})
const average = (arr) => {
return _.sum(arr) / arr.length
}
const percentile = (sortedArr, p) => {
const i = Math.floor(p / 100 * (sortedArr.length - 1))
return Math.round(sortedArr[i])
}
const getResultsFromHar = (har) => {
// HAR 1.2 Spec: http://www.softwareishard.com/blog/har-12-spec/
const { entries } = har.log
const results = {}
const first = entries[0]
const last = entries[entries.length - 1]
const elapsed = Number(new Date(last.startedDateTime)) + last.time - Number(new Date(first.startedDateTime))
results['Total'] = Math.round(elapsed)
let mins = {}
let maxes = {}
const timings = {
'receive': [],
'wait': [],
'send': [],
'total': [],
}
entries.forEach((entry) => {
const blockedTime = _.get(entry.timings, 'blocked', -1) === -1 ? 0 : entry.timings.blocked
const totalTime = entry.time - blockedTime
timings.total.push(totalTime)
Object.keys(entry.timings).forEach((timingKey) => {
if (entry.timings[timingKey] === -1 || !entry.timings[timingKey]) return
const ms = Math.round(entry.timings[timingKey])
if (timings[timingKey]) timings[timingKey].push(ms)
})
})
for (const key in timings) {
const arr = timings[key]
arr.sort((a, b) => {
return a - b
})
mins[key] = Math.round(arr[0])
maxes[key] = Math.round(arr[arr.length - 1])
_.merge(results, {
[`Avg ${_.upperFirst(key)}`]: Math.round(average(arr)),
})
}
results['Min'] = mins.total
expect(timings.total.length).to.be.at.least(1000)
;[1, 5, 25, 50, 75, 95, 99, 99.7].forEach((p) => {
results[`${p}% <=`] = percentile(timings.total, p)
})
results['Max'] = maxes.total
return results
}
const runBrowserTest = (urlUnderTest, testCase) => {
const cdpPort = CDP_PORT + Math.round(Math.random() * 10000)
const browser = {
isHeadless: true,
}
const options = {}
const args = _getArgs(browser, options, cdpPort).concat([
// additionally...
'--disable-background-networking',
'--no-sandbox', // allows us to run as root, for CI
`--user-data-dir=${fse.mkdtempSync(path.join(os.tmpdir(), 'cy-perf-'))}`,
])
if (testCase.disableHttp2) {
args.push('--disable-http2')
}
if (testCase.cyProxy) {
args.push(`--proxy-server=http://localhost:${CY_PROXY_PORT}`)
}
if (testCase.upstreamProxy && !testCase.cyProxy) {
args.push(`--proxy-server=http://localhost:${PROXY_PORT}`)
} else if (testCase.httpsUpstreamProxy && !testCase.cyProxy) {
args.push(`--proxy-server=https://localhost:${HTTPS_PROXY_PORT}`)
}
if (testCase.upstreamProxy && testCase.cyProxy) {
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `http://localhost:${PROXY_PORT}`
} else if (testCase.httpsUpstreamProxy && testCase.cyProxy) {
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `https://localhost:${HTTPS_PROXY_PORT}`
} else {
delete process.env.HTTPS_PROXY
delete process.env.HTTP_PROXY
}
if (testCase.cyIntercept) {
cyServer.remoteStates.set(urlUnderTest)
} else {
cyServer.remoteStates.set('<root>')
}
let cmd = CHROME_PATH
debug('Launching Chrome: ', cmd, args.join(' '))
const proc = cp.spawn(cmd, args, {
stdio: 'ignore',
})
const storeHar = Promise.method((name, har) => {
const artifacts = process.env.CIRCLE_ARTIFACTS
if (artifacts) {
return fse.ensureDir(artifacts)
.then(() => {
const pathToFile = path.join(artifacts, sanitizeFilename(`${name}.har`))
debug('saving har to path:', pathToFile)
return fse.writeJson(pathToFile, har)
})
}
})
const runHar = () => {
// wait for Chrome to open, then start capturing
return Promise.delay(500).then(() => {
debug('Trying to connect to Chrome...')
const harCapturer = HarCapturer.run([
urlUnderTest,
], {
port: cdpPort,
// disable SSL verification on older Chrome versions, copied from the HAR CLI
// https://github.com/cyrus-and/chrome-har-capturer/blob/587550508bddc23b7f4b4328c158322be4749298/bin/cli.js#L60
preHook: (_, cdp) => {
const { Security } = cdp
return Security.enable().then(() => {
return Security.setOverrideCertificateErrors({ override: true })
})
.then(() => {
return Security.certificateError(({ eventId }) => {
debug('EVENT ID', eventId)
return Security.handleCertificateError({ eventId, action: 'continue' })
})
})
},
// wait til all data is done before finishing
// https://github.com/cyrus-and/chrome-har-capturer/issues/59
postHook: (_, cdp) => {
let timeout
return new Promise((resolve) => {
cdp.on('event', (message) => {
if (message.method === 'Network.dataReceived') {
// reset timer
clearTimeout(timeout)
timeout = setTimeout(resolve, 1000)
}
})
})
},
})
return new Promise((resolve, reject) => {
harCapturer.on('fail', (_, err) => {
return reject(err)
})
harCapturer.on('har', resolve)
})
.then((har) => {
proc.kill(9)
debug('Received HAR from Chrome')
const results = getResultsFromHar(har)
_.merge(testCase, results)
return storeHar(testCase.name, har)
.return(results)
})
.catch({ code: 'ECONNREFUSED' }, (err) => {
// sometimes chrome takes surprisingly long, just reconn
debug('Chrome connection failed: ', err)
return runHar()
})
})
}
return runHar()
}
let cyServer
describe('Proxy Performance', function () {
this.timeout(60 * 1000)
this.retries(3)
beforeEach(function () {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
nock.enableNetConnect()
})
before(function () {
setCtx(makeDataContext({}))
const getFilesByGlob = getCtx().file.getFilesByGlob
return CA.create()
.then((ca) => {
return ca.generateServerCertificateKeys('localhost')
})
.spread((cert, key) => {
return Promise.join(
new DebuggingProxy().start(PROXY_PORT),
new DebuggingProxy({
https: { cert, key },
}).start(HTTPS_PROXY_PORT),
setupFullConfigWithDefaults({
projectRoot: '/tmp/a',
config: {
supportFile: false,
},
}, getFilesByGlob).then((config) => {
config.port = CY_PROXY_PORT
// turn off morgan
config.morgan = false
cyServer = new ServerBase()
return cyServer.open(config, {
SocketCtor: SocketE2E,
createRoutes,
testingType: 'e2e',
getCurrentBrowser: () => null,
})
}),
)
})
})
URLS_UNDER_TEST.map((urlUnderTest) => {
// TODO: fix flaky tests https://github.com/cypress-io/cypress/issues/23214
describe(urlUnderTest, { retries: 15 }, function () {
let baseline
const testCases = _.cloneDeep(TEST_CASES)
before(function () {
// run baseline test
return runBrowserTest(urlUnderTest, testCases[0])
.then((runtime) => {
debug('baseline runtime is: ', runtime)
baseline = runtime
})
})
// slice(1) since first test is used as baseline above
testCases.slice(1).map((testCase) => {
let multiplier = 3
if (testCase.httpsUpstreamProxy) {
// there is extra slowdown when the HTTPS upstream is used, so slightly increase the multiplier
// maybe from higher CPU utilization with debugging-proxy and HTTPS
multiplier *= 1.5
}
it(`${testCase.name} loads 1000 images less than ${multiplier}x as slowly as Chrome`, function () {
debug('Current test: ', testCase.name)
return runBrowserTest(urlUnderTest, testCase)
.then((results) => {
expect(results['Total']).to.be.lessThan(multiplier * baseline['Total'])
})
})
})
after(() => {
debug(`Done in ${Math.round((new Date() / 1000) - start)}s`)
process.stdout.write('Note: All times are in milliseconds.\n')
// eslint-disable-next-line no-console
console.table(testCases)
return Promise.map(testCases, (testCase) => {
testCase['URL'] = urlUnderTest
return performance.track('Proxy Performance', testCase)
})
})
})
})
})