Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1243 lines (1094 loc) · 33.8 KB
/
Copy pathmain.go
File metadata and controls
1243 lines (1094 loc) · 33.8 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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"os/signal"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
// headerFlag permite passar -H "Key: Value" repetidas vezes
type headerFlag []string
func (h *headerFlag) String() string { return strings.Join(*h, ", ") }
func (h *headerFlag) Set(value string) error {
*h = append(*h, value)
return nil
}
// RequestLogEntry representa uma entrada de log para cada request
type RequestLogEntry struct {
Timestamp string `json:"timestamp"`
RequestNum int `json:"request_num"`
URL string `json:"url"`
Method string `json:"method"`
StatusCode int `json:"status_code,omitempty"`
ResponseTimeMs int64 `json:"response_time_ms"`
ResponseBytes int `json:"response_bytes,omitempty"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
RequestBody string `json:"request_body,omitempty"`
ResponseBody string `json:"response_body,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
}
// Logger ultra-performático com canal e worker dedicado
type RequestLogger struct {
file *os.File
logChan chan RequestLogEntry
done chan struct{}
buffer *bufio.Writer
encoder *json.Encoder
}
// Pool de strings.Builder para reutilização e redução de alocações
var stringBuilderPool = sync.Pool{
New: func() any {
return &strings.Builder{}
},
}
// getBuilder obtém um Builder do pool
func getBuilder() *strings.Builder {
sb := stringBuilderPool.Get().(*strings.Builder)
sb.Reset()
return sb
}
// putBuilder devolve o Builder ao pool
func putBuilder(sb *strings.Builder) {
stringBuilderPool.Put(sb)
}
// NewRequestLogger cria um novo logger com arquivo timestampado e worker dedicado
func NewRequestLogger() (*RequestLogger, error) {
timestamp := time.Now().Format("20060102_150405")
filename := fmt.Sprintf("%s.log", timestamp)
file, err := os.Create(filename)
if err != nil {
return nil, fmt.Errorf("erro ao criar arquivo de log: %w", err)
}
buffer := bufio.NewWriterSize(file, 256*1024) // buffer de 256KB
encoder := json.NewEncoder(buffer)
logger := &RequestLogger{
file: file,
logChan: make(chan RequestLogEntry, 10000), // buffer de 10k requests
done: make(chan struct{}),
buffer: buffer,
encoder: encoder,
}
// iniciar worker dedicado para escrita
go logger.logWorker()
return logger, nil
}
// logWorker processa logs de forma assíncrona em uma única goroutine
func (l *RequestLogger) logWorker() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case entry := <-l.logChan:
// escrever no encoder (já serializa para JSON)
l.encoder.Encode(entry)
case <-ticker.C:
// flush periódico para garantir que os dados sejam escritos
l.buffer.Flush()
case <-l.done:
// processar logs pendentes antes de fechar
for {
select {
case entry := <-l.logChan:
l.encoder.Encode(entry)
default:
l.buffer.Flush()
return
}
}
}
}
}
// LogAsync envia uma entrada de log para o canal (não-bloqueante, extremamente rápido)
func (l *RequestLogger) LogAsync(entry RequestLogEntry) {
// copiar entry para evitar race conditions
entryCopy := RequestLogEntry{
Timestamp: entry.Timestamp,
RequestNum: entry.RequestNum,
URL: entry.URL,
Method: entry.Method,
StatusCode: entry.StatusCode,
ResponseTimeMs: entry.ResponseTimeMs,
ResponseBytes: entry.ResponseBytes,
Success: entry.Success,
Error: entry.Error,
RequestBody: entry.RequestBody,
ResponseBody: entry.ResponseBody,
Variables: make(map[string]string),
}
// copiar mapa de variáveis
for k, v := range entry.Variables {
entryCopy.Variables[k] = v
}
// enviar para canal (não bloqueia se canal estiver cheio)
select {
case l.logChan <- entryCopy:
default:
// canal cheio, descarta (em alta performance, melhor perder um log que travar)
}
}
// PendingLogs retorna o número aproximado de logs pendentes no canal
func (l *RequestLogger) PendingLogs() int {
return len(l.logChan)
}
// Close fecha o logger de forma graceful
func (l *RequestLogger) Close() error {
close(l.done) // sinaliza para worker parar
time.Sleep(200 * time.Millisecond) // aguarda worker processar logs pendentes
close(l.logChan) // fecha o canal
if err := l.buffer.Flush(); err != nil {
return err
}
return l.file.Close()
}
func main() {
var (
concurrency = flag.Int("c", 50, "number of concurrent workers")
durationStr = flag.String("d", "10s", "test duration (e.g. 30s, 1m)")
timeout = flag.Duration("t", 5*time.Second, "per-request timeout")
method = flag.String("m", "GET", "HTTP method to use")
headers headerFlag
fillMode = flag.Bool("fill", false, "interactive placeholder fill mode: read request from stdin and substitute [[var]] tokens")
fillFile = flag.String("f", "", "file to read request from (optional, reads from stdin if not specified)")
fillWorkers = flag.Int("w", 50, "number of concurrent workers in fill mode (default: 50)")
perfMode = flag.Bool("P", false, "performance mode: no logging, discard responses (maximum speed)")
)
flag.Var(&headers, "H", "header to add to request, can be repeated: -H 'Authorization: Bearer x' -H 'Accept: application/json'")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] <url>\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if *fillMode {
runInteractiveFill(*fillFile, *fillWorkers, *perfMode)
return
}
if flag.NArg() < 1 {
flag.Usage()
os.Exit(2)
}
url := flag.Arg(0)
// parse duration
dur, err := time.ParseDuration(*durationStr)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid duration: %v\n", err)
os.Exit(2)
}
// configure HTTP client for high throughput
tr := &http.Transport{
MaxIdleConns: 100000,
MaxIdleConnsPerHost: *concurrency * 4,
MaxConnsPerHost: *concurrency * 4,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
DisableCompression: true,
}
client := &http.Client{Transport: tr, Timeout: *timeout}
var (
totalRequests int64
successRequests int64
failedRequests int64
totalBytes int64
totalLatencyNs int64
maxLatencyNs int64
)
ctx, cancel := context.WithTimeout(context.Background(), dur)
defer cancel()
// handle interrupt to stop early
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
go func() {
select {
case <-sigCh:
fmt.Fprintln(os.Stderr, "\ninterrupted, stopping...")
cancel()
case <-ctx.Done():
}
}()
// start workers
var wg sync.WaitGroup
wg.Add(*concurrency)
for i := 0; i < *concurrency; i++ {
go func(workerID int) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
}
start := time.Now()
req, err := http.NewRequestWithContext(ctx, strings.ToUpper(*method), url, nil)
if err != nil {
atomic.AddInt64(&failedRequests, 1)
atomic.AddInt64(&totalRequests, 1)
continue
}
for _, h := range headers {
parts := strings.SplitN(h, ":", 2)
if len(parts) == 2 {
req.Header.Add(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
}
}
resp, err := client.Do(req)
elapsed := time.Since(start)
atomic.AddInt64(&totalRequests, 1)
atomic.AddInt64(&totalLatencyNs, elapsed.Nanoseconds())
// update max latency
for {
old := atomic.LoadInt64(&maxLatencyNs)
if elapsed.Nanoseconds() <= old {
break
}
if atomic.CompareAndSwapInt64(&maxLatencyNs, old, elapsed.Nanoseconds()) {
break
}
}
if err != nil {
atomic.AddInt64(&failedRequests, 1)
continue
}
// count body bytes and close
n, _ := io.Copy(io.Discard, resp.Body)
resp.Body.Close()
atomic.AddInt64(&totalBytes, n)
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
atomic.AddInt64(&successRequests, 1)
} else {
atomic.AddInt64(&failedRequests, 1)
}
}
}(i)
}
// reporting loop
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
var prevTotal int64
var prevLatencyNs int64
var prevBytes int64
startTime := time.Now()
for {
select {
case <-ctx.Done():
wg.Wait()
printSummary(&totalRequests, &successRequests, &failedRequests, &totalBytes, &totalLatencyNs, &maxLatencyNs, startTime)
return
case <-ticker.C:
curTotal := atomic.LoadInt64(&totalRequests)
curSuccess := atomic.LoadInt64(&successRequests)
curFailed := atomic.LoadInt64(&failedRequests)
curBytes := atomic.LoadInt64(&totalBytes)
curLatency := atomic.LoadInt64(&totalLatencyNs)
curMax := atomic.LoadInt64(&maxLatencyNs)
delta := curTotal - prevTotal
deltaBytes := curBytes - prevBytes
deltaLatency := curLatency - prevLatencyNs
prevTotal = curTotal
prevBytes = curBytes
prevLatencyNs = curLatency
avgLatency := time.Duration(0)
if delta > 0 {
avgLatency = time.Duration(deltaLatency / delta)
} else if curTotal > 0 {
avgLatency = time.Duration(curLatency / curTotal)
}
fmt.Printf("[%.0fs] total=%d (+%d/s) success=%d fail=%d bytes=%.1fKB/s avg=%s max=%s\n",
time.Since(startTime).Seconds(), curTotal, delta, curSuccess, curFailed, float64(deltaBytes)/1024.0, avgLatency, time.Duration(curMax))
}
}
}
func printSummary(totalPtr, successPtr, failedPtr, bytesPtr, latencyPtr, maxLatencyPtr *int64, start time.Time) {
total := atomic.LoadInt64(totalPtr)
success := atomic.LoadInt64(successPtr)
failed := atomic.LoadInt64(failedPtr)
bytes := atomic.LoadInt64(bytesPtr)
latency := atomic.LoadInt64(latencyPtr)
maxLatency := atomic.LoadInt64(maxLatencyPtr)
d := time.Since(start)
avgLatency := time.Duration(0)
if total > 0 {
avgLatency = time.Duration(latency / total)
}
fmt.Println("----- SUMMARY -----")
fmt.Printf("duration: %s\n", d)
fmt.Printf("requests: %d\n", total)
fmt.Printf("success: %d\n", success)
fmt.Printf("failed: %d\n", failed)
fmt.Printf("bytes: %.1f KB\n", float64(bytes)/1024.0)
fmt.Printf("avg latency: %s\n", avgLatency)
fmt.Printf("max latency: %s\n", time.Duration(maxLatency))
fmt.Println("-------------------")
}
// parseVariableDefinitions extrai definições de variáveis no formato [var]="regex"
// de uma string. Retorna um map com as definições encontradas.
func parseVariableDefinitions(input string) map[string]string {
definitions := make(map[string]string)
// regex para encontrar [variavel]="valor"
re := regexp.MustCompile(`\[([a-zA-Z0-9_\-]+)\]\s*=\s*"([^"]*)"`)
matches := re.FindAllStringSubmatch(input, -1)
for _, match := range matches {
if len(match) >= 3 {
varName := match[1]
value := match[2]
definitions[varName] = value
}
}
return definitions
}
// RequestJob representa um trabalho de request para ser processado por workers
type RequestJob struct {
requestNum int
values map[string]string
}
// RequestResult representa o resultado de uma request para ser logado
type RequestResult struct {
timestamp time.Time
requestNum int
url string
method string
requestBody string
statusCode int
responseBody string
responseBytes int
responseTimeMs int64
success bool
err error
variables map[string]string
}
// runInteractiveFill lê uma request colada da entrada padrão ou de um arquivo,
// detecta tokens [[nome]] e interage com o usuário para obter uma regex ou um valor direto para substituir.
// Se filepath for fornecido, lê do arquivo. Caso contrário, lê de stdin.
// Executa com workers paralelos para máxima performance.
// Se perfMode = true, não cria logs e descarta respostas para máxima velocidade.
func runInteractiveFill(filepath string, numWorkers int, perfMode bool) {
var input string
if filepath != "" {
// ler do arquivo
data, err := os.ReadFile(filepath)
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao ler arquivo %s: %v\n", filepath, err)
os.Exit(1)
}
input = string(data)
fmt.Fprintf(os.Stderr, "Lendo request de: %s\n", filepath)
} else {
// ler de stdin
fmt.Fprintln(os.Stderr, "Cole a request do Chrome DevTools (formato fetch(...)) e tecle Ctrl-D:")
input = readStdinAll()
}
// parsear definições de variáveis do arquivo/input
predefinedVars := parseVariableDefinitions(input)
// parsear a request
req, err := parseFetchRequest(input)
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao parsear request: %v\n", err)
os.Exit(1)
}
// encontrar placeholders [[var]] em toda a request
placeholderRe := regexp.MustCompile(`\[\[([a-zA-Z0-9_\-]+)\]\]`)
// buscar em url, headers e body
fullText := req.URL + "\n" + req.Body
for k, v := range req.Headers {
fullText += k + ":" + v + "\n"
}
matches := placeholderRe.FindAllStringSubmatch(fullText, -1)
// map para armazenar as regexes/valores (não os valores gerados ainda)
regexPatterns := map[string]string{}
reader := bufio.NewReader(os.Stdin)
rand.Seed(time.Now().UnixNano())
// coletar regexes/valores únicos
seen := map[string]bool{}
for _, m := range matches {
key := m[1]
if seen[key] {
continue
}
seen[key] = true
// verificar se já tem definição no arquivo
if predefinedValue, exists := predefinedVars[key]; exists {
regexPatterns[key] = predefinedValue
fmt.Fprintf(os.Stderr, "\n[[%s]] = \"%s\" (definido no arquivo)\n", key, predefinedValue)
// fazer um teste de geração se for regex
if looksLikeRegex(predefinedValue) {
gen, err := generateFromSimpleRegex(predefinedValue)
if err != nil {
fmt.Fprintf(os.Stderr, "⚠ Aviso: erro ao testar regex: %v\n", err)
} else {
fmt.Fprintf(os.Stderr, "✓ Exemplo: %s\n", gen)
}
}
continue
}
// se não está definido, perguntar ao usuário
fmt.Fprintf(os.Stderr, "\nPlaceholder: [[%s]]\n", key)
fmt.Fprintln(os.Stderr, "Digite uma regex para gerar (ex: \\d{8}, [a-z]{6}) ou valor literal:")
fmt.Fprint(os.Stderr, "> ")
line, _ := reader.ReadString('\n')
line = strings.TrimSpace(line)
if line == "" {
regexPatterns[key] = ""
continue
}
// armazenar a regex ou valor literal (não gerar ainda)
regexPatterns[key] = line
// fazer um teste de geração se for regex
if looksLikeRegex(line) {
gen, err := generateFromSimpleRegex(line)
if err != nil {
fmt.Fprintf(os.Stderr, "⚠ Aviso: erro ao testar regex: %v\n", err)
} else {
fmt.Fprintf(os.Stderr, "✓ Exemplo: %s\n", gen)
}
}
}
// perguntar quantas vezes executar
fmt.Fprint(os.Stderr, "\nQuantas vezes executar a request? ")
line, _ := reader.ReadString('\n')
iterations, err := strconv.Atoi(strings.TrimSpace(line))
if err != nil || iterations <= 0 {
fmt.Fprintln(os.Stderr, "Valor inválido, usando 1")
iterations = 1
}
// perguntar delay entre requests
fmt.Fprint(os.Stderr, "Delay entre requests em ms (0 = máximo de velocidade): ")
line, _ = reader.ReadString('\n')
delayMs, err := strconv.Atoi(strings.TrimSpace(line))
if err != nil || delayMs < 0 {
delayMs = 0
}
delay := time.Duration(delayMs) * time.Millisecond
// usar todos os cores disponíveis (importante para performance)
runtime.GOMAXPROCS(runtime.NumCPU())
// criar logger apenas se não estiver em modo performance
var logger *RequestLogger
if !perfMode {
var err error
logger, err = NewRequestLogger()
if err != nil {
fmt.Fprintf(os.Stderr, "Aviso: não foi possível criar arquivo de log: %v\n", err)
fmt.Fprintln(os.Stderr, "Continuando sem logging...")
} else {
defer logger.Close()
fmt.Fprintf(os.Stderr, "📝 Log será salvo em: %s\n", logger.file.Name())
fmt.Fprintf(os.Stderr, "💡 Dica: Para performance máxima, use -P (modo performance sem logs)\n")
}
} else {
fmt.Fprintf(os.Stderr, "⚡ MODO PERFORMANCE ATIVADO - Sem logging, descartando respostas\n")
fmt.Fprintf(os.Stderr, "⚡ Configuração: conexões ilimitadas, sem timeouts, fire-and-forget mode\n")
fmt.Fprintf(os.Stderr, "⚡ Dica: Para performance máxima, aumente ulimit -n (file descriptors)\n")
}
// criar cliente HTTP otimizado para alta concorrência
var client *http.Client
if perfMode {
// MODO ULTRA PERFORMANCE: sem limites, sem timeouts, conexões ilimitadas
client = &http.Client{
Timeout: 0, // sem timeout
Transport: &http.Transport{
MaxIdleConns: 0, // ilimitado
MaxIdleConnsPerHost: 0, // ilimitado
MaxConnsPerHost: 0, // ilimitado
IdleConnTimeout: 0, // ilimitado
DisableCompression: true, // sem compressão para speed
DisableKeepAlives: false, // keep-alive ativado
ResponseHeaderTimeout: 0, // sem timeout
ExpectContinueTimeout: 0, // sem timeout
ForceAttemptHTTP2: true, // tentar HTTP/2 para multiplexing
},
}
} else {
// MODO NORMAL OTIMIZADO: limites altos mas com timeouts razoáveis
client = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100000, // aumentado de 10000
MaxIdleConnsPerHost: numWorkers * 4, // aumentado de *2 para *4
MaxConnsPerHost: numWorkers * 4, // aumentado de *2 para *4
IdleConnTimeout: 90 * time.Second,
DisableCompression: true, // sem compressão para speed
DisableKeepAlives: false, // keep-alive ativado
ResponseHeaderTimeout: 10 * time.Second, // timeout de header
ForceAttemptHTTP2: true, // tentar HTTP/2
},
}
}
// contadores atômicos para estatísticas
var (
successCount int64
failCount int64
completed int64
)
// otimizar número de workers baseado no modo
actualWorkers := numWorkers
if perfMode {
if numWorkers < 500 {
actualWorkers = 500 // mínimo de 500 workers em modo performance
fmt.Fprintf(os.Stderr, "⚡ Modo Performance: aumentando workers para %d\n", actualWorkers)
}
} else {
// modo normal: sugerir no mínimo 100 workers para boa performance
if numWorkers < 100 {
actualWorkers = 100
fmt.Fprintf(os.Stderr, "🚀 Otimização: aumentando workers para %d (use -w para customizar)\n", actualWorkers)
}
}
fmt.Fprintf(os.Stderr, "\n=== Executando %d requests com %d workers paralelos ===\n\n", iterations, actualWorkers)
// canal de jobs para distribuir trabalho
// em modo performance, usar canal menor ou sem buffer
jobsChanSize := iterations
if perfMode {
jobsChanSize = actualWorkers * 2 // canal menor em modo performance
}
jobs := make(chan RequestJob, jobsChanSize)
// canal de resultados para logging (apenas em modo normal)
var resultsChan chan RequestResult
if !perfMode {
resultsChan = make(chan RequestResult, actualWorkers*10) // buffer grande para não bloquear
}
// iniciar workers de logging (separados das requests)
numLogWorkers := 10 // workers dedicados apenas para logging
var logWg sync.WaitGroup
if !perfMode && logger != nil {
for i := 0; i < numLogWorkers; i++ {
logWg.Add(1)
go func() {
defer logWg.Done()
for result := range resultsChan {
// criar entrada de log
logEntry := RequestLogEntry{
Timestamp: result.timestamp.Format(time.RFC3339Nano),
RequestNum: result.requestNum,
URL: result.url,
Method: result.method,
ResponseTimeMs: result.responseTimeMs,
Variables: result.variables,
StatusCode: result.statusCode,
ResponseBytes: result.responseBytes,
Success: result.success,
}
// incluir bodies
if result.requestBody != "" {
logEntry.RequestBody = result.requestBody
}
if result.responseBody != "" {
logEntry.ResponseBody = result.responseBody
}
if result.err != nil {
logEntry.Error = result.err.Error()
}
// salvar no log
logger.LogAsync(logEntry)
}
}()
}
}
// canal de resultados (opcional, apenas para tracking)
var wg sync.WaitGroup
// iniciar workers
for w := 0; w < actualWorkers; w++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
for job := range jobs {
currentValues := job.values
// criar cópias da request com novos valores
currentURL := placeholderRe.ReplaceAllStringFunc(req.URL, func(s string) string {
sub := placeholderRe.FindStringSubmatch(s)
if len(sub) >= 2 {
if v, ok := currentValues[sub[1]]; ok {
return v
}
}
return s
})
currentBody := placeholderRe.ReplaceAllStringFunc(req.Body, func(s string) string {
sub := placeholderRe.FindStringSubmatch(s)
if len(sub) >= 2 {
if v, ok := currentValues[sub[1]]; ok {
return v
}
}
return s
})
currentHeaders := make(map[string]string)
for k, v := range req.Headers {
currentHeaders[k] = placeholderRe.ReplaceAllStringFunc(v, func(s string) string {
sub := placeholderRe.FindStringSubmatch(s)
if len(sub) >= 2 {
if val, ok := currentValues[sub[1]]; ok {
return val
}
}
return s
})
}
// criar e executar request HTTP
var bodyReader io.Reader
if currentBody != "" {
bodyReader = strings.NewReader(currentBody)
}
httpReq, err := http.NewRequest(req.Method, currentURL, bodyReader)
if err != nil {
atomic.AddInt64(&failCount, 1)
atomic.AddInt64(&completed, 1)
continue
}
for k, v := range currentHeaders {
httpReq.Header.Set(k, v)
}
if perfMode {
// MODO ULTRA PERFORMANCE: fire and forget, sem esperar resposta
go func() {
resp, err := client.Do(httpReq)
if err == nil {
resp.Body.Close() // fechar imediatamente sem ler
atomic.AddInt64(&successCount, 1)
} else {
atomic.AddInt64(&failCount, 1)
}
atomic.AddInt64(&completed, 1)
}()
} else {
// MODO NORMAL OTIMIZADO: request rápida + envia resultado para workers de log
go func(reqCopy *http.Request, jobNum int, vals map[string]string, url, body string) {
start := time.Now()
resp, err := client.Do(reqCopy)
elapsed := time.Since(start)
if err != nil {
atomic.AddInt64(&failCount, 1)
atomic.AddInt64(&completed, 1)
// enviar resultado com erro para logging
if resultsChan != nil {
select {
case resultsChan <- RequestResult{
timestamp: start,
requestNum: jobNum,
url: url,
method: req.Method,
requestBody: body,
responseTimeMs: elapsed.Milliseconds(),
success: false,
err: err,
variables: vals,
}:
default:
// canal cheio, descarta
}
}
return
}
// ler resposta rapidamente
respBody, _ := io.ReadAll(resp.Body)
resp.Body.Close()
success := resp.StatusCode < 400
if success {
atomic.AddInt64(&successCount, 1)
} else {
atomic.AddInt64(&failCount, 1)
}
atomic.AddInt64(&completed, 1)
// enviar resultado para workers de logging (não-bloqueante)
if resultsChan != nil {
select {
case resultsChan <- RequestResult{
timestamp: start,
requestNum: jobNum,
url: url,
method: req.Method,
requestBody: body,
statusCode: resp.StatusCode,
responseBody: string(respBody),
responseBytes: len(respBody),
responseTimeMs: elapsed.Milliseconds(),
success: success,
variables: vals,
}:
default:
// canal cheio, descarta log mas continua
}
}
}(httpReq, job.requestNum, currentValues, currentURL, currentBody)
// delay entre requests (se configurado)
// nota: delay aplica ao disparo, não à conclusão
if delay > 0 {
time.Sleep(delay)
}
}
}
}(w)
}
// gerar jobs e enviar para os workers
startTime := time.Now()
for i := 0; i < iterations; i++ {
// gerar novos valores para cada request
currentValues := make(map[string]string)
for key, pattern := range regexPatterns {
if looksLikeRegex(pattern) {
gen, err := generateFromSimpleRegex(pattern)
if err != nil {
currentValues[key] = pattern
} else {
currentValues[key] = gen
}
} else {
currentValues[key] = pattern
}
}
jobs <- RequestJob{
requestNum: i + 1,
values: currentValues,
}
}
close(jobs)
// reporter thread para mostrar progresso em tempo real
done := make(chan struct{})
go func() {
// em modo performance, atualizar menos frequentemente para economizar CPU
reportInterval := 500 * time.Millisecond
if perfMode {
reportInterval = 2 * time.Second // menos frequente em modo performance
}
ticker := time.NewTicker(reportInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c := atomic.LoadInt64(&completed)
s := atomic.LoadInt64(&successCount)
f := atomic.LoadInt64(&failCount)
pct := float64(c) / float64(iterations) * 100
fmt.Fprintf(os.Stderr, "\r[%.1f%%] Completo: %d | Sucesso: %d | Falha: %d", pct, c, s, f)
case <-done:
return
}
}
}()
// aguardar workers terminarem de disparar
wg.Wait()
// aguardar todas as requests completarem (com timeout de segurança)
fmt.Fprintf(os.Stderr, "\n⏳ Aguardando conclusão de todas as requests...\n")
waitStart := time.Now()
maxWaitTime := 5 * time.Minute // timeout de 5 minutos
for {
c := atomic.LoadInt64(&completed)
if c >= int64(iterations) {
break
}
// verificar timeout
if time.Since(waitStart) > maxWaitTime {
fmt.Fprintf(os.Stderr, "\n⚠️ Timeout: nem todas as requests completaram em %s\n", maxWaitTime)
break
}
time.Sleep(100 * time.Millisecond)
// mostrar progresso enquanto aguarda
s := atomic.LoadInt64(&successCount)
f := atomic.LoadInt64(&failCount)
pct := float64(c) / float64(iterations) * 100
fmt.Fprintf(os.Stderr, "\r[%.1f%%] Completo: %d | Sucesso: %d | Falha: %d", pct, c, s, f)
}
close(done)
// fechar canal de resultados e aguardar workers de logging terminarem
if !perfMode && resultsChan != nil {
fmt.Fprintf(os.Stderr, "\n💾 Finalizando processamento de logs...\n")
close(resultsChan) // fecha canal, sinalizando para workers pararem
logWg.Wait() // aguarda workers de logging terminarem
// aguardar até que o canal de logs do logger esteja vazio
if logger != nil {
maxLogWait := 30 * time.Second
logWaitStart := time.Now()
for {
pending := logger.PendingLogs()
if pending == 0 {
break
}
if time.Since(logWaitStart) > maxLogWait {
fmt.Fprintf(os.Stderr, "⚠️ Aviso: ainda há ~%d logs pendentes após %s\n", pending, maxLogWait)
break
}
fmt.Fprintf(os.Stderr, "\r💾 Aguardando escrita de ~%d logs...", pending)
time.Sleep(200 * time.Millisecond)
}
// aguardar flush final
time.Sleep(500 * time.Millisecond)
fmt.Fprintf(os.Stderr, "\r✅ Todos os logs foram escritos! \n")
}
}
elapsed := time.Since(startTime)
finalCompleted := atomic.LoadInt64(&completed)
finalSuccess := atomic.LoadInt64(&successCount)
finalFailed := atomic.LoadInt64(&failCount)
reqPerSec := float64(finalCompleted) / elapsed.Seconds()
fmt.Fprintf(os.Stderr, "\n\n=== Resumo ===\n")
fmt.Fprintf(os.Stderr, "Total Disparado: %d | Completado: %d\n", iterations, finalCompleted)
fmt.Fprintf(os.Stderr, "Sucesso: %d | Falha: %d\n", finalSuccess, finalFailed)
fmt.Fprintf(os.Stderr, "Tempo total: %s\n", elapsed)
fmt.Fprintf(os.Stderr, "Requests/segundo: %.2f\n", reqPerSec)
if logger != nil {
fmt.Fprintf(os.Stderr, "📄 Log salvo em: %s\n", logger.file.Name())
}
}
type FetchRequest struct {
URL string
Method string
Headers map[string]string
Body string
}
// parseFetchRequest extrai informações da request fetch() colada
func parseFetchRequest(input string) (*FetchRequest, error) {
req := &FetchRequest{
Method: "GET",
Headers: make(map[string]string),
}
// extrair URL - primeira string após fetch(
urlRe := regexp.MustCompile(`fetch\s*\(\s*["']([^"']+)["']`)
urlMatch := urlRe.FindStringSubmatch(input)
if len(urlMatch) < 2 {
return nil, fmt.Errorf("URL não encontrada no fetch()")
}
req.URL = urlMatch[1]
// extrair method
methodRe := regexp.MustCompile(`["']method["']\s*:\s*["']([^"']+)["']`)
if methodMatch := methodRe.FindStringSubmatch(input); len(methodMatch) >= 2 {
req.Method = strings.ToUpper(methodMatch[1])
}
// extrair headers
headersRe := regexp.MustCompile(`["']headers["']\s*:\s*\{([^}]+)\}`)
if headersMatch := headersRe.FindStringSubmatch(input); len(headersMatch) >= 2 {
headerBlock := headersMatch[1]
headerLineRe := regexp.MustCompile(`["']([^"']+)["']\s*:\s*["']([^"']*)["']`)
for _, match := range headerLineRe.FindAllStringSubmatch(headerBlock, -1) {
if len(match) >= 3 {
req.Headers[match[1]] = match[2]
}
}
}
// extrair body - melhor handling de strings com escape
bodyRe := regexp.MustCompile(`["']body["']\s*:\s*["']((?:[^"'\\]|\\.)*)["']`)
if bodyMatch := bodyRe.FindStringSubmatch(input); len(bodyMatch) >= 2 {
body := bodyMatch[1]
// decodificar escapes: \" para " e \\ para \
body = strings.ReplaceAll(body, `\"`, `"`)
body = strings.ReplaceAll(body, `\\`, `\`)
req.Body = body