Files
mtusi2026lab3/student-tests/loadgen.go
T

131 lines
4.3 KiB
Go

// Independent standard-library load generator. Configuration (including token)
// arrives on stdin and is never echoed. Uses persistent HTTP connections to LB.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
)
type config struct {
BaseURL string `json:"base_url"`
Token string `json:"token"`
Chat string `json:"chat"`
Concurrency int `json:"concurrency"`
Duration float64 `json:"duration"`
Warmup float64 `json:"warmup"`
RunID string `json:"run_id"`
}
type result struct {
Elapsed float64 `json:"elapsed_seconds"`
Concurrency int `json:"concurrency"`
Success int `json:"successful_requests"`
Errors int `json:"failed_requests"`
RPS float64 `json:"successful_rps"`
ErrorRatio float64 `json:"error_ratio"`
Latency map[string]float64 `json:"all_attempt_latency_ms"`
Statuses map[string]int `json:"statuses"`
Instances map[string]int `json:"instances"`
PerSecond []map[string]int `json:"per_second"`
}
func main() {
var c config
if json.NewDecoder(os.Stdin).Decode(&c) != nil || c.Concurrency < 1 || c.Duration < 1 || c.Token == "" {
fmt.Fprintln(os.Stderr, "Invalid benchmark configuration")
os.Exit(1)
}
transport := &http.Transport{MaxIdleConns: 512, MaxIdleConnsPerHost: 512, MaxConnsPerHost: 512, IdleConnTimeout: 30 * time.Second}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
var sequence atomic.Uint64
phase := func(seconds float64, measure bool) result {
start := time.Now()
deadline := start.Add(time.Duration(seconds * float64(time.Second)))
r := result{Concurrency: c.Concurrency, Statuses: map[string]int{}, Instances: map[string]int{},
PerSecond: make([]map[string]int, int(math.Ceil(seconds))+6)}
for i := range r.PerSecond {
r.PerSecond[i] = map[string]int{"success": 0, "error": 0}
}
var latencies []float64
var mu sync.Mutex
var wg sync.WaitGroup
for worker := 0; worker < c.Concurrency; worker++ {
wg.Add(1)
go func() {
defer wg.Done()
for time.Now().Before(deadline) {
n := sequence.Add(1)
now := time.Now()
// 80% reads, 20% durable writes. Text has a fixed 200-byte size.
method, path := "GET", "/api/v1/chats/"+c.Chat+"/messages?limit=50"
var body io.Reader
if n%5 == 0 {
method, path = "POST", "/api/v1/chats/"+c.Chat+"/messages"
body = bytes.NewReader([]byte(`{"text":"` + string(bytes.Repeat([]byte("x"), 200)) + `"}`))
}
req, _ := http.NewRequest(method, c.BaseURL+path, body)
req.Header.Set("Authorization", "Bearer "+c.Token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", c.RunID+":"+strconv.FormatUint(n, 10))
resp, err := client.Do(req)
status, instance := "network", ""
ok := false
if err == nil {
_, readErr := io.Copy(io.Discard, resp.Body)
resp.Body.Close()
status = strconv.Itoa(resp.StatusCode)
instance = resp.Header.Get("X-Instance-Id")
ok = readErr == nil && ((method == "GET" && resp.StatusCode == 200) || (method == "POST" && resp.StatusCode == 201))
}
if measure {
mu.Lock()
latencies = append(latencies, float64(time.Since(now).Microseconds())/1000)
r.Statuses[status]++
if instance != "" {
r.Instances[instance]++
}
bucket := int(time.Since(start).Seconds())
if bucket >= len(r.PerSecond) {
bucket = len(r.PerSecond) - 1
}
if ok {
r.Success++
r.PerSecond[bucket]["success"]++
} else {
r.Errors++
r.PerSecond[bucket]["error"]++
}
mu.Unlock()
}
}
}()
}
wg.Wait()
r.Elapsed = time.Since(start).Seconds()
r.RPS = float64(r.Success) / r.Elapsed
if r.Success+r.Errors > 0 {
r.ErrorRatio = float64(r.Errors) / float64(r.Success+r.Errors)
}
if measure && len(latencies) > 0 {
sort.Float64s(latencies)
r.Latency = map[string]float64{}
for name, p := range map[string]float64{"p50": .5, "p95": .95, "p99": .99} {
r.Latency[name] = latencies[int(math.Ceil(float64(len(latencies))*p))-1]
}
}
return r
}
phase(c.Warmup, false)
json.NewEncoder(os.Stdout).Encode(phase(c.Duration, true))
}