-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathindex.html
More file actions
806 lines (749 loc) · 37.2 KB
/
index.html
File metadata and controls
806 lines (749 loc) · 37.2 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
<!DOCTYPE html>
<html :lang="currentLanguage" style="height: 100%">
<head>
<!-- Meta tags for responsive design -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- External dependencies -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- Custom Styles -->
<style>
:root {
--primary: #667eea;
--gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--danger: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
--shadow: 0 10px 40px rgba(0,0,0,0.15);
--radius: 16px;
--text-main: #333;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--gradient);
min-height: 100vh;
padding: 10px;
color: var(--text-main);
}
.main-container { max-width: 1400px; margin: 0 auto; }
/* Headers */
.page-header {
text-align: center; color: white; margin-bottom: 10px;
animation: fadeInDown 0.6s ease-out;
}
.page-header h2 { font-size: 2rem; margin-bottom: 10px; text-shadow: 2px 2px 4px rgba(0,0,0,0.2); }
.page-header p { opacity: 0.9; font-size: 1.1rem; }
/* Cards & Panels */
.chart-card, .control-panel, .stat-card {
background: white;
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 10px;
margin-bottom: 10px;
animation: fadeInUp 0.6s ease-out;
}
.control-panel { padding: 10px; }
.chart-card-header, .control-header {
display: flex; justify-content: space-between; align-items: center;
margin-bottom: 10px; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0;
}
.chart-card-title, .control-title { font-size: 1.3rem; font-weight: 600; }
/* Buttons */
.button-group { display: flex; gap: 10px; margin-bottom: 10px; }
.button-group .el-button {
flex: 1; height: 50px; font-size: 16px; border-radius: 10px; border: none;
transition: transform 0.3s, box-shadow 0.3s;
margin-left: 0px;
}
.button-group .el-button:hover { transform: translateY(-2px); }
.button-group .el-button--primary { background: var(--gradient); }
.button-group .el-button--primary:hover { box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4); }
.button-group .el-button--danger { background: var(--danger); }
.button-group .el-button--danger:hover:not(:disabled) { box-shadow: 0 8px 20px rgba(245, 87, 108, 0.4); }
/* Forms */
.form-section { margin-bottom: 10px; }
.section-title {
font-size: 1.1rem; font-weight: 600; color: #555;
margin-bottom: 10px; padding-left: 10px; border-left: 4px solid var(--primary);
}
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px; }
.form-item-full { grid-column: 1 / -1; }
.el-input, .el-select { margin: 0 !important; }
.el-input__inner, .el-textarea__inner {
border-radius: 8px; border: 2px solid #e8e8e8; transition: all 0.3s;
}
.el-input__inner:focus, .el-textarea__inner:focus {
border-color: var(--primary); box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.el-input-group__prepend {
background: var(--gradient); color: white; border: none; font-weight: 600; border-radius: 8px 0 0 8px;
}
.language-selector .el-input__inner {
background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); color: white; font-weight: 600;
}
.charts-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; animation-fill-mode: both; }
/* Animations */
@keyframes fadeInDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } }
@keyframes fadeInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
/* Responsive */
@media (max-width: 992px) { .charts-row { grid-template-columns: 1fr; } }
@media (max-width: 768px) {
.page-header h2 { font-size: 1.5rem; }
.button-group, .form-grid { flex-direction: column; }
.control-panel { padding: 20px; }
}
</style>
<script type="text/javascript">
// i18n configuration for multilingual support
const translations = {
'zh-CN': {
title: '🚀 HTTP 压力测试工具',
subtitle: '专业的HTTP/1/2/3性能测试工具',
start: '开始压测',
stop: '停止压测',
chart: {
title: '⚡️ 实时性能指标',
qps: 'QPS',
statusCode: '状态码',
latency: '⏱️ 响应耗时分布',
errorDist: '🚫 错误分布'
},
stats: {
avg: '平均耗时',
rps: '平均 QPS',
fastest: '最快耗时',
slowest: '最慢耗时',
errors: '错误总数'
},
section: {
testConfig: '⚙️ 测试配置',
requestConfig: '🌐 请求配置',
stressParams: '⚡ 压测参数',
advancedSettings: '🔧 高级设置'
},
metrics: {
duration: '采集间隔(毫秒)',
durationPlaceholder: '监控数据刷新间隔,默认2000ms'
},
request: {
url: '请求地址',
urlPlaceholder: '请输入压测目标URL',
method: '请求方法',
methodPlaceholder: '选择请求方法',
body: '请求体',
bodyPlaceholder: '请输入请求体内容',
bodyType: '请求体类型',
bodyTypePlaceholder: '空或hex,默认空',
type: '协议类型',
typePlaceholder: 'http1, http2, ws, wss,默认http1'
},
stress: {
total: '总请求数',
totalPlaceholder: '0 = 无限制',
concurrent: '并发数',
concurrentPlaceholder: '1-10000',
duration: '持续时间(毫秒)',
durationPlaceholder: '毫秒',
timeout: '超时时间(毫秒)',
timeoutPlaceholder: '毫秒',
qps: 'QPS限制',
qpsPlaceholder: '0 = 无限制',
worker: 'Worker API',
workerPlaceholder: '/api 或自定义端点'
},
advanced: {
compression: '禁用压缩',
keepalive: '禁用Keep-Alive',
auth: '认证信息',
username: '用户名',
password: '密码'
},
message: {
start: '压测已开始',
stop: '压测已停止',
error: '压测错误',
success: '操作成功',
warning: '警告',
info: '提示'
},
validation: {
urlRequired: '请输入请求地址',
urlInvalid: '请输入有效的URL',
concurrentInvalid: '并发数必须在1-10000之间',
durationInvalid: '持续时间必须大于0'
}
},
'en-US': {
title: '🚀 HTTP Benchmark Tool',
subtitle: 'Professional HTTP Performance Testing Tool',
start: 'Start Test',
stop: 'Stop Test',
chart: {
title: '📊 Real-time Performance Metrics',
qps: 'QPS',
statusCode: 'Status Code',
latency: '📊 Latency Distribution',
errorDist: '⚠️ Error Distribution'
},
stats: {
avg: 'Average Latency',
rps: 'Average RPS',
fastest: 'Fastest Request',
slowest: 'Slowest Request',
errors: 'Total Errors'
},
section: {
testConfig: '⚙️ Test Configuration',
requestConfig: '🌐 Request Configuration',
stressParams: '⚡ Stress Test Parameters',
advancedSettings: '🔧 Advanced Settings'
},
metrics: {
duration: 'Metrics Interval (MS)',
durationPlaceholder: 'Metrics refresh interval, default 2000ms'
},
request: {
url: 'Request URL',
urlPlaceholder: 'Enter target URL for stress test',
method: 'Request Method',
methodPlaceholder: 'Select HTTP method',
body: 'Request Body',
bodyPlaceholder: 'Enter request body content',
bodyType: 'Body Type',
bodyTypePlaceholder: 'empty or hex, default empty',
type: 'Protocol Type',
typePlaceholder: 'http1, http2, ws, wss, default http1'
},
stress: {
total: 'Total Requests',
totalPlaceholder: '0 = unlimited',
concurrent: 'Concurrent Connections',
concurrentPlaceholder: '1-10000',
duration: 'Duration (MS)',
durationPlaceholder: 'milliseconds',
timeout: 'Timeout (MS)',
timeoutPlaceholder: 'milliseconds',
qps: 'QPS Limit',
qpsPlaceholder: '0 = unlimited',
worker: 'Worker API',
workerPlaceholder: '/api or custom endpoint'
},
advanced: {
compression: 'Disable Compression',
keepalive: 'Disable Keep-Alive',
auth: 'Authentication',
username: 'Username',
password: 'Password'
},
message: {
start: 'Benchmark test started',
stop: 'Benchmark test stopped',
error: 'Benchmark test error',
success: 'Operation successful',
warning: 'Warning',
info: 'Information'
},
validation: {
urlRequired: 'Please enter request URL',
urlInvalid: 'Please enter a valid URL',
concurrentInvalid: 'Concurrent connections must be between 1-10000',
durationInvalid: 'Duration must be greater than 0'
}
}
};
</script>
<title id="page-title">HTTP Benchmark Tool</title>
</head>
<body>
<!-- Page Header -->
<div class="page-header">
<h2 id="page-title">🚀 HTTP Benchmark Tool</h2>
<p id="page-subtitle">Professional HTTP1/2/3 Performance Testing Tool</p>
</div>
<div class="main-container" id="app">
<!-- Chart Card -->
<div class="chart-card">
<div class="chart-card-header">
<div class="chart-card-title" id="chart-title">📊 Real-time Performance Metrics</div>
</div>
<div id="chart-container" style="height: 400px; width: 100%;"></div>
</div>
<!-- Secondary Charts -->
<div class="charts-row" v-show="hasData" style="display: none;" :style="{ display: hasData ? 'grid' : 'none' }">
<div class="chart-card">
<div class="chart-card-header">
<div class="chart-card-title">{{translate('chart.latency')}}</div>
</div>
<div id="latency-chart" style="height: 350px; width: 100%;"></div>
</div>
<div class="chart-card">
<div class="chart-card-header">
<div class="chart-card-title">{{translate('chart.errorDist')}}</div>
</div>
<div id="error-chart" style="height: 350px; width: 100%;"></div>
</div>
</div>
<!-- Control Panel (Vue App) -->
<div>
<div class="control-panel">
<!-- Language selector -->
<div style="position: absolute; top: 30px; right: 30px; width: 120px;">
<el-select v-model="currentLanguage" @change="changeLanguage" size="small" class="language-selector">
<el-option label="🇨🇳 中文" value="zh-CN"></el-option>
<el-option label="🇺🇸 English" value="en-US"></el-option>
</el-select>
</div>
<div class="control-header">
<div class="control-title" id="control-title">⚙️ Test Configuration</div>
</div>
<!-- Control Buttons -->
<div class="button-group">
<el-button type="primary" :loading="isRunning" @click="startTest" icon="el-icon-video-play">
{{translate('start')}}
</el-button>
<el-button type="danger" @click="stopTest" :disabled="!isRunning" icon="el-icon-video-pause">
{{translate('stop')}}
</el-button>
</div>
<!-- Request Configuration Section -->
<div class="form-section">
<div class="section-title" id="section-request">🌐 Request Configuration</div>
<div class="form-grid">
<div class="form-item-full">
<el-input :placeholder="translate('request.urlPlaceholder')" v-model="requestUrl">
<template slot="prepend">{{translate('request.url')}}</template>
</el-input>
</div>
<el-select v-model="protocolType" :placeholder="translate('request.typePlaceholder')" style="width: 100%;">
<template slot="prepend">{{translate('request.type')}}</template>
<el-option
v-for="protocol in protocolOptions"
:key="protocol.value"
:label="protocol.label"
:value="protocol.value">
</el-option>
</el-select>
<el-select v-model="requestMethod" :placeholder="translate('request.methodPlaceholder')" style="width: 100%;">
<template slot="prepend">{{translate('request.method')}}</template>
<el-option
v-for="method in httpMethods"
:key="method.value"
:label="method.label"
:value="method.value">
</el-option>
</el-select>
<div class="form-item-full">
<el-input :placeholder="translate('request.bodyPlaceholder')" v-model="requestBody" type="textarea"
:autosize="{ minRows: 3, maxRows: 10}">
<template slot="prepend">{{translate('request.body')}}</template>
</el-input>
</div>
<el-input :placeholder="translate('request.bodyTypePlaceholder')" v-model="requestBodyType">
<template slot="prepend">{{translate('request.bodyType')}}</template>
</el-input>
</div>
</div>
<!-- Stress Test Parameters Section -->
<div class="form-section">
<div class="section-title" id="section-stress">⚡ Stress Test Parameters</div>
<div class="form-grid">
<el-input :placeholder="translate('stress.totalPlaceholder')" v-model="totalRequests" type="number">
<template slot="prepend">{{translate('stress.total')}}</template>
</el-input>
<el-input :placeholder="translate('stress.concurrentPlaceholder')" v-model="concurrentConnections" type="number">
<template slot="prepend">{{translate('stress.concurrent')}}</template>
</el-input>
<el-input :placeholder="translate('stress.durationPlaceholder')" v-model="testDuration" type="number">
<template slot="prepend">{{translate('stress.duration')}}</template>
</el-input>
<el-input :placeholder="translate('stress.timeoutPlaceholder')" v-model="requestTimeout" type="number">
<template slot="prepend">{{translate('stress.timeout')}}</template>
</el-input>
<el-input :placeholder="translate('stress.qpsPlaceholder')" v-model="qpsLimit" type="number">
<template slot="prepend">{{translate('stress.qps')}}</template>
</el-input>
<el-input :placeholder="translate('metrics.durationPlaceholder')" v-model="metricsInterval" type="number">
<template slot="prepend">{{translate('metrics.duration')}}</template>
</el-input>
</div>
</div>
<!-- Advanced Settings Section -->
<div class="form-section">
<div class="section-title" id="section-advanced">🔧 Advanced Settings</div>
<div class="form-grid">
<div class="form-item-full">
<el-input :placeholder="translate('stress.workerPlaceholder')" v-model="workerApiEndpoint">
<template slot="prepend">{{translate('stress.worker')}}</template>
</el-input>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// Date formatting utility
Date.prototype.format = function (fmt) {
const formatOptions = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let key in formatOptions) {
if (new RegExp("(" + key + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1,
(RegExp.$1.length === 1) ?
(formatOptions[key]) :
(("00" + formatOptions[key]).substr(("" + formatOptions[key]).length)));
}
}
return fmt;
};
// Constants
const API_COMMANDS = {
START: 0,
STOP: 1,
GET_METRICS: 2
};
const DEFAULT_API_PATH = "/api";
const CONTENT_TYPE_JSON = { 'Content-Type': 'application/json;charset=utf-8' };
const DEFAULT_METRICS_INTERVAL = 2000;
const TIME_FORMAT = "hh:mm:ss";
// Helper functions
const formatDuration = ns => {
if (!ns) return '0ms';
if (ns < 1e6) return (ns / 1e3).toFixed(2) + 'µs';
if (ns < 1e9) return (ns / 1e6).toFixed(2) + 'ms';
return (ns / 1e9).toFixed(2) + 's';
};
const debounce = (fn, delay) => {
let timer = null;
return function() {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, arguments), delay);
};
};
// Vue application instance
new Vue({
el: '#app',
data: {
// Application state
currentLanguage: 'zh-CN',
metricsInterval: DEFAULT_METRICS_INTERVAL,
requestMethod: "GET",
requestBody: "",
requestBodyType: "",
protocolType: "http1",
protocolOptions: [
{ value: 'http1', label: 'HTTP(S) / 1.1' },
{ value: 'http2', label: 'HTTP(S) / 2' },
{ value: 'http3', label: 'HTTP(S) / 3' },
{ value: 'ws', label: 'WebSocket(ws://)' },
{ value: 'wss', label: 'WebSocket Secure(wss://)' }
],
httpMethods: [
{ value: 'OPTIONS', label: 'OPTIONS' },
{ value: 'GET', label: 'GET' },
{ value: 'HEAD', label: 'HEAD' },
{ value: 'POST', label: 'POST' },
{ value: 'PUT', label: 'PUT' },
{ value: 'DELETE', label: 'DELETE' },
{ value: 'TRACE', label: 'TRACE' },
{ value: 'CONNECT', label: 'CONNECT' }
],
totalRequests: 0,
concurrentConnections: 1,
testDuration: 10000,
requestTimeout: 3000,
qpsLimit: 0,
disableCompression: false,
disableKeepalives: false,
authUsername: "",
authPassword: "",
requestUrl: "https://www.http3check.net",
workerApiEndpoint: "",
isRunning: false,
metricsTimer: undefined,
hasData: false,
stats: { average: '0ms', rps: 0, fastest: '0ms', slowest: '0ms', errTotal: 0 },
charts: {},
monitor: {
timeLabels: [],
qpsData: [],
total: 0,
statusCodes: {},
prevStatusCounts: {}
}
},
methods: {
// i18n translation method
translate(key) {
const keyParts = key.split('.');
let translation = translations[this.currentLanguage];
for (const part of keyParts) {
translation = translation[part];
if (!translation) break;
}
return translation || key;
},
// Switch language
changeLanguage(language) {
this.currentLanguage = language;
localStorage.setItem('preferred-language', language);
// Update all static text elements
this.updateStaticTexts();
document.documentElement.setAttribute('lang', language);
},
// Update static text elements
updateStaticTexts() {
document.getElementById('page-title').innerText = this.translate('title');
document.getElementById('page-subtitle').innerText = this.translate('subtitle');
document.getElementById('chart-title').innerText = this.translate('chart.title');
document.getElementById('control-title').innerText = this.translate('section.testConfig');
document.getElementById('section-request').innerText = this.translate('section.requestConfig');
document.getElementById('section-stress').innerText = this.translate('section.stressParams');
document.getElementById('section-advanced').innerText = this.translate('section.advancedSettings');
},
// Show message
showMessage(messageKey, type = 'success', duration = 2000) {
this.$message({
showClose: true,
message: this.translate(`${messageKey}`) || messageKey,
type: type,
duration: duration,
});
},
// Start stress test
startTest() {
this.sequenceId = Math.floor(Math.random() * 1000000) + 1;
// Build request data
const requestData = this.buildRequestData(API_COMMANDS.START);
const apiEndpoint = this.getWorkerApiEndpoint();
this.showMessage('start');
// Send start stress test request
fetch(apiEndpoint, {
method: 'POST',
headers: CONTENT_TYPE_JSON,
body: JSON.stringify(requestData)
})
.then(response => response.json())
.then(data => {
if (data.err_code !== 0) {
this.isRunning = false;
this.metricsTimer && clearInterval(this.metricsTimer);
this.showMessage(data.err_msg, 'error', 5000);
return;
}
})
.catch(error => {
this.showMessage(error.message, 'error', 5000);
this.isRunning = false;
});
// Setup monitoring
this.setupMetricsMonitoring(requestData, apiEndpoint);
},
// Build request data
buildRequestData(command) {
return {
cmd: command,
sequence_id: this.sequenceId,
request_method: this.requestMethod,
request_body: this.requestBody,
request_bodytype: this.requestBodyType,
request_type: this.protocolType,
n: parseInt(this.totalRequests) || 0,
c: parseInt(this.concurrentConnections) || 1,
duration: parseInt(this.testDuration) * 1000000 || 1000 * 1000000,
timeout: parseInt(this.requestTimeout) * 1000000 || 3000 * 1000000,
qps: parseInt(this.qpsLimit) || 0,
disable_compression: this.disableCompression || this.disableCompression === "true",
disable_keepalives: this.disableKeepalives || this.disableKeepalives === "true",
auth_username: this.authUsername,
auth_password: this.authPassword,
url: this.requestUrl,
from: 'browser',
};
},
// Get Worker API address
getWorkerApiEndpoint() {
return this.workerApiEndpoint.length > 0 ? this.workerApiEndpoint : DEFAULT_API_PATH;
},
initCharts() {
const init = (id) => {
const el = document.getElementById(id);
if (!el) return null;
try {
return echarts.init(el, 'dark', { renderer: 'canvas', useDirtyRect: false });
} catch (e) {
console.error('Failed to init chart:', id, e);
return null;
}
};
this.charts = {
perf: init('chart-container'),
lat: init('latency-chart'),
err: init('error-chart')
};
this.renderPerfChart([], []);
},
renderPerfChart(times, qps, status = {}) {
if (!this.charts.perf) return;
const series = [{ name: "qps", data: qps, type: 'line', smooth: true }];
const legend = ['qps'];
Object.keys(status).forEach(code => {
series.push({ name: code, data: status[code], type: 'line', smooth: true });
legend.push(code);
});
this.charts.perf.setOption({
legend: { data: legend },
tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
xAxis: { type: 'category', data: times },
yAxis: { type: 'value' },
series
});
},
renderLatChart(lats) {
if (!this.charts.lat || !lats) return;
const entries = Object.entries(lats).map(([k, v]) => ({ val: parseInt(k)/1e6, count: v }));
if (!entries.length) return;
const min = Math.min(...entries.map(e => e.val));
const max = Math.max(...entries.map(e => e.val));
const buckets = 20;
const step = (max - min) / buckets || 1;
const data = new Array(buckets).fill(0);
const cats = new Array(buckets).fill(0).map((_, i) => `${(min + i*step).toFixed(1)}-${(min + (i+1)*step).toFixed(1)}ms`);
entries.forEach(e => {
let idx = Math.floor((e.val - min) / step);
if (idx >= buckets) idx = buckets - 1;
data[idx] += e.count;
});
this.charts.lat.setOption({
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: { type: 'category', data: cats, axisLabel: { interval: 'auto', rotate: 30 } },
yAxis: { type: 'value' },
series: [{ name: 'Count', type: 'bar', data, itemStyle: { color: '#667eea' } }]
});
},
renderErrChart(dist) {
if (!this.charts.err || !dist) return;
const data = Object.entries(dist).map(([name, value]) => ({ value, name }));
this.charts.err.setOption({
tooltip: { trigger: 'item' },
legend: { top: '5%', left: 'center' },
series: [{
name: 'Errors', type: 'pie', radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: { label: { show: true, fontSize: '14', fontWeight: 'bold' } },
data
}]
});
},
setupMetricsMonitoring(requestData, apiEndpoint) {
this.monitor = { timeLabels: [], qpsData: [], total: 0, statusCodes: {}, prevStatusCounts: {} };
const interval = parseInt(this.metricsInterval) || DEFAULT_METRICS_INTERVAL;
let errTimes = 0;
this.isRunning = true;
this.metricsTimer = setInterval(() => {
fetch(apiEndpoint, {
method: 'POST',
headers: CONTENT_TYPE_JSON,
body: JSON.stringify({ ...requestData, cmd: API_COMMANDS.GET_METRICS })
})
.then(r => r.json())
.then(data => {
if (data.err_code !== 0) {
if (++errTimes > 2) {
this.stopTest();
this.showMessage(data.err_msg, 'error', 5000);
}
return;
}
errTimes = 0;
this.processMetricsData(data, interval);
})
.catch(e => console.error("Metrics fetch failed:", e));
}, interval);
},
processMetricsData(data, interval) {
if (!data) return;
if (!this.hasData) {
this.hasData = true;
this.$nextTick(() => {
Object.values(this.charts).forEach(c => c && c.resize());
});
}
if (data.is_last) {
this.stopTest();
return;
}
this.stats = {
average: formatDuration(data.average),
rps: data.rps || 0,
fastest: formatDuration(data.fastest),
slowest: formatDuration(data.slowest),
errTotal: data.err_total || 0
};
this.renderLatChart(data.lats);
this.renderErrChart(data.error_dist);
if (data.lats_total && (data.lats_total - this.monitor.total) >= 0) {
this.monitor.timeLabels.push(new Date().format(TIME_FORMAT));
const currentQps = (data.lats_total - this.monitor.total) * 1000 / interval;
this.monitor.qpsData.push(currentQps);
this.monitor.total = data.lats_total;
if (data.status_code_dist) {
for (let code in data.status_code_dist) {
if (!this.monitor.statusCodes[code]) this.monitor.statusCodes[code] = [];
const count = data.status_code_dist[code];
const prev = this.monitor.prevStatusCounts[code] || 0;
this.monitor.statusCodes[code].push((count - prev) * 1000 / interval);
this.monitor.prevStatusCounts[code] = count;
}
}
this.renderPerfChart(this.monitor.timeLabels, this.monitor.qpsData, this.monitor.statusCodes);
}
},
stopTest() {
this.showMessage('stop');
this.isRunning = false;
clearInterval(this.metricsTimer);
this.metricsTimer = undefined;
fetch(this.getWorkerApiEndpoint(), {
method: 'POST',
headers: CONTENT_TYPE_JSON,
body: JSON.stringify(this.buildRequestData(API_COMMANDS.STOP))
}).catch(e => console.error(e));
}
},
created() {
// Load saved language preference
const savedLanguage = localStorage.getItem('preferred-language');
if (savedLanguage && translations[savedLanguage]) {
this.currentLanguage = savedLanguage;
}
},
mounted() {
this.$nextTick(() => {
this.initCharts();
this.updateStaticTexts();
window.addEventListener('resize', debounce(() => {
Object.values(this.charts).forEach(c => c && c.resize());
}, 250));
});
document.documentElement.setAttribute('lang', this.currentLanguage);
}
});
</script>
</body>
</html>