forked from Windshiftapp/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstress_load.go
More file actions
254 lines (216 loc) · 6.29 KB
/
stress_load.go
File metadata and controls
254 lines (216 loc) · 6.29 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
//go:build ignore
// +build ignore
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
type StressTestResults struct {
TotalRequests int64
SuccessfulRequests int64
FailedRequests int64
DatabaseErrors int64
TimeoutErrors int64
AverageLatency time.Duration
MaxLatency time.Duration
MinLatency time.Duration
RequestsPerSecond float64
}
type RequestMetrics struct {
latency time.Duration
success bool
error string
}
func main() {
baseURL := "http://localhost:8080"
if len(os.Args) > 1 {
baseURL = os.Args[1]
}
fmt.Println("Starting Windshift Dual-Pool Stress Test")
fmt.Println("========================================")
// Test scenarios focusing on database connection pooling
scenarios := []struct {
name string
concurrency int
duration time.Duration
endpoint string
method string
body interface{}
}{
{
name: "Permission Read Load (Read Pool Test)",
concurrency: 50,
duration: 30 * time.Second,
endpoint: "/api/permissions",
method: "GET",
},
{
name: "Mixed Read/Write (Pool Separation Test)",
concurrency: 100,
duration: 60 * time.Second,
endpoint: "/api/users/1/permissions", // Mix of reads
method: "GET",
},
{
name: "High Concurrency Reads (120+ connections)",
concurrency: 150,
duration: 45 * time.Second,
endpoint: "/api/permissions",
method: "GET",
},
}
for _, scenario := range scenarios {
fmt.Printf("\n📊 Running: %s\n", scenario.name)
fmt.Printf(" Concurrency: %d, Duration: %v\n", scenario.concurrency, scenario.duration)
results := runStressTest(baseURL, scenario.endpoint, scenario.method, scenario.body,
scenario.concurrency, scenario.duration)
printResults(results)
// Cool down between tests
fmt.Println(" ⏳ Cooling down...")
time.Sleep(5 * time.Second)
}
fmt.Println("\nTesting Complete!")
fmt.Println("\nKey Metrics to Watch:")
fmt.Println("• Database Errors: Should be 0 with dual pools")
fmt.Println("• Timeout Errors: Should be minimal with 5s timeout")
fmt.Println("• Request/sec: Should be higher with read pool scaling")
fmt.Println("• Latency: Should be more consistent")
}
func runStressTest(baseURL, endpoint, method string, body interface{}, concurrency int, duration time.Duration) StressTestResults {
var (
totalRequests int64
successfulRequests int64
failedRequests int64
databaseErrors int64
timeoutErrors int64
totalLatency int64
maxLatency time.Duration
minLatency = time.Duration(1<<63 - 1) // Max duration
)
client := &http.Client{
Timeout: 10 * time.Second,
}
// Channel to collect metrics
metricsChan := make(chan RequestMetrics, concurrency*2)
// Worker pool
var wg sync.WaitGroup
// Start time
startTime := time.Now()
endTime := startTime.Add(duration)
// Launch workers
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
for time.Now().Before(endTime) {
start := time.Now()
// Create request
var req *http.Request
var err error
if body != nil {
bodyBytes, _ := json.Marshal(body)
req, err = http.NewRequest(method, baseURL+endpoint, bytes.NewBuffer(bodyBytes))
req.Header.Set("Content-Type", "application/json")
} else {
req, err = http.NewRequest(method, baseURL+endpoint, nil)
}
if err != nil {
metricsChan <- RequestMetrics{
latency: time.Since(start),
success: false,
error: "request_creation_failed",
}
continue
}
// Execute request
resp, err := client.Do(req)
latency := time.Since(start)
atomic.AddInt64(&totalRequests, 1)
if err != nil {
metricsChan <- RequestMetrics{
latency: latency,
success: false,
error: "request_failed",
}
if isTimeoutError(err) {
atomic.AddInt64(&timeoutErrors, 1)
}
atomic.AddInt64(&failedRequests, 1)
continue
}
success := resp.StatusCode < 400
var errorType string
if !success {
if resp.StatusCode == 500 {
errorType = "database_error"
atomic.AddInt64(&databaseErrors, 1)
} else {
errorType = fmt.Sprintf("http_%d", resp.StatusCode)
}
atomic.AddInt64(&failedRequests, 1)
} else {
atomic.AddInt64(&successfulRequests, 1)
}
resp.Body.Close()
metricsChan <- RequestMetrics{
latency: latency,
success: success,
error: errorType,
}
// Brief pause to prevent overwhelming
time.Sleep(time.Millisecond)
}
}(i)
}
// Metrics collector
go func() {
wg.Wait()
close(metricsChan)
}()
// Process metrics
for metric := range metricsChan {
atomic.AddInt64(&totalLatency, int64(metric.latency))
if metric.latency > maxLatency {
maxLatency = metric.latency
}
if metric.latency < minLatency {
minLatency = metric.latency
}
}
totalDuration := time.Since(startTime)
return StressTestResults{
TotalRequests: totalRequests,
SuccessfulRequests: successfulRequests,
FailedRequests: failedRequests,
DatabaseErrors: databaseErrors,
TimeoutErrors: timeoutErrors,
AverageLatency: time.Duration(totalLatency / totalRequests),
MaxLatency: maxLatency,
MinLatency: minLatency,
RequestsPerSecond: float64(totalRequests) / totalDuration.Seconds(),
}
}
func printResults(results StressTestResults) {
fmt.Printf(" Results:\n")
fmt.Printf(" Total Requests: %d\n", results.TotalRequests)
fmt.Printf(" Successful: %d (%.1f%%)\n", results.SuccessfulRequests,
float64(results.SuccessfulRequests)/float64(results.TotalRequests)*100)
fmt.Printf(" Failed: %d (%.1f%%)\n", results.FailedRequests,
float64(results.FailedRequests)/float64(results.TotalRequests)*100)
fmt.Printf(" Database Errors: %d\n", results.DatabaseErrors)
fmt.Printf(" Timeout Errors: %d\n", results.TimeoutErrors)
fmt.Printf(" Requests/sec: %.1f\n", results.RequestsPerSecond)
fmt.Printf(" Avg Latency: %v\n", results.AverageLatency)
fmt.Printf(" Min/Max Latency: %v / %v\n", results.MinLatency, results.MaxLatency)
}
func isTimeoutError(err error) bool {
return strings.Contains(err.Error(), "timeout") ||
strings.Contains(err.Error(), "deadline exceeded")
}