forked from mtusi2026/mtusi2026lab3
На 5
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"encoding/json"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/outside"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
|
||||
@@ -25,6 +26,8 @@ import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
"github.com/google/uuid"
|
||||
stdhttp "net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -41,9 +44,27 @@ func run() error {
|
||||
return fmt.Errorf("load server config: %w", err)
|
||||
}
|
||||
|
||||
if len(os.Args) > 1 && os.Args[1] == "migrate" {
|
||||
cfg.Postgres.RunMigrations = true
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
return migrator.New(cfg).Start(ctx)
|
||||
}
|
||||
// API processes never run migrations; the one-shot migrator owns schema changes.
|
||||
cfg.Postgres.RunMigrations = false
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(cfg.Application.LogLevel)); err != nil {
|
||||
return err
|
||||
}
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})))
|
||||
hostname, _ := os.Hostname()
|
||||
instanceID := hostname + "-" + uuid.NewString()
|
||||
slog.Info("instance_started", "instance_id", instanceID)
|
||||
pgx := postgres.New(cfg.Postgres)
|
||||
rx := cache.New(cfg)
|
||||
postgresMigrator := migrator.New(cfg)
|
||||
defer pgx.Close()
|
||||
defer rx.Close()
|
||||
tm := txmanager.New(pgx)
|
||||
provider := jwtprovider.New(cfg)
|
||||
encryptor := encrypting.New()
|
||||
@@ -61,10 +82,15 @@ func run() error {
|
||||
|
||||
httpRouter := router.New(
|
||||
middleware.NewAuthMiddleware(authSvc),
|
||||
middleware.Instance(instanceID),
|
||||
middleware.RequestIDMiddleware(),
|
||||
middleware.LoggingMiddleware(),
|
||||
middleware.RequestTimeout(cfg.Postgres.QueryTimeout),
|
||||
)
|
||||
httpRouter.Get("/internal/metrics", func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
stat := pgx.Stat()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"instance_id": instanceID, "acquire_count": stat.AcquireCount(), "acquire_duration_ns": stat.AcquireDuration().Nanoseconds(), "empty_acquire_count": stat.EmptyAcquireCount(), "acquired_conns": stat.AcquiredConns(), "total_conns": stat.TotalConns(), "max_conns": stat.MaxConns()})
|
||||
})
|
||||
server := http.New(cfg, httpRouter)
|
||||
requestValidator := validator.NewValidatorImpl()
|
||||
registerRoutes(
|
||||
|
||||
+202
-328
@@ -1,386 +1,260 @@
|
||||
// Command benchmark measures the lab1 HTTP API in fresh, resource-limited containers.
|
||||
// Command benchmark generates paced lab3 traffic through the public load balancer.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
container = "mtusi-inmemory-benchmark"
|
||||
baseURL = "http://127.0.0.1:18093"
|
||||
)
|
||||
|
||||
type runResult struct {
|
||||
History int `json:"history"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
Repetition int `json:"repetition"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
ReadSuccess int `json:"read_success"`
|
||||
WriteSuccess int `json:"write_success"`
|
||||
Errors int `json:"errors"`
|
||||
SuccessfulRPS float64 `json:"successful_rps"`
|
||||
LatencyMS map[string]float64 `json:"latency_ms"`
|
||||
RSSBeforeKiB int `json:"rss_kib_before"`
|
||||
RSSPeakKiB int `json:"rss_kib_peak"`
|
||||
type client struct {
|
||||
base, token string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
type report struct {
|
||||
Image string `json:"image"`
|
||||
Method map[string]any `json:"method"`
|
||||
Runs []runResult `json:"runs"`
|
||||
}
|
||||
|
||||
type workerResult struct {
|
||||
reads int
|
||||
writes int
|
||||
errors int
|
||||
latencies []float64
|
||||
}
|
||||
|
||||
type memoryResult struct {
|
||||
peak int
|
||||
err error
|
||||
}
|
||||
|
||||
func docker(args ...string) (string, error) {
|
||||
command := exec.Command("docker", args...)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("docker %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
func rssKiB() (int, error) {
|
||||
status, err := docker("exec", container, "cat", "/proc/1/status")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for line := range strings.SplitSeq(status, "\n") {
|
||||
if strings.HasPrefix(line, "VmRSS:") {
|
||||
fields := strings.Fields(line)
|
||||
return strconv.Atoi(fields[1])
|
||||
}
|
||||
}
|
||||
return 0, errors.New("VmRSS is unavailable")
|
||||
}
|
||||
|
||||
func newClient(timeout time.Duration) *http.Client {
|
||||
return &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxConnsPerHost: 1,
|
||||
MaxIdleConnsPerHost: 1,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func request(client *http.Client, method, path, user string, body any) (map[string]any, error) {
|
||||
func (c *client) call(method, path string, body any, key string) (map[string]any, int, error) {
|
||||
var data io.Reader
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
b, e := json.Marshal(body)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
data = bytes.NewReader(encoded)
|
||||
data = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, baseURL+path, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if user != "" {
|
||||
req.Header.Set("X-User-Id", user)
|
||||
req, e := http.NewRequest(method, c.base+path, data)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
|
||||
return nil, fmt.Errorf("%s %s: HTTP %d: %s", method, path, response.StatusCode, content)
|
||||
// net/http otherwise treats Idempotency-Key + GetBody as permission to retry POST.
|
||||
if method == http.MethodPost {
|
||||
req.GetBody = nil
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(content, &payload); err != nil {
|
||||
return nil, err
|
||||
resp, e := c.http.Do(req)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
return payload, nil
|
||||
defer resp.Body.Close()
|
||||
b, e := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if e != nil {
|
||||
return nil, resp.StatusCode, e
|
||||
}
|
||||
if resp.StatusCode != 200 && resp.StatusCode != 201 {
|
||||
return nil, resp.StatusCode, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var out map[string]any
|
||||
e = json.Unmarshal(b, &out)
|
||||
return out, resp.StatusCode, e
|
||||
}
|
||||
|
||||
func stringField(payload map[string]any, key string) (string, error) {
|
||||
value, ok := payload[key].(string)
|
||||
if !ok || value == "" {
|
||||
return "", fmt.Errorf("missing %s in API response", key)
|
||||
func (c *client) setup(seed int) (string, error) {
|
||||
username := "bench_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
|
||||
password := "Synthetic-benchmark-123"
|
||||
user, _, e := c.call("POST", "/api/v1/users", map[string]string{"username": username, "display_name": "Benchmark", "password": password}, "")
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func percentile(sorted []float64, proportion float64) float64 {
|
||||
if len(sorted) == 0 {
|
||||
return 0
|
||||
req, _ := http.NewRequest("POST", c.base+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth(username, password)
|
||||
resp, e := c.http.Do(req)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
index := int(math.Ceil(float64(len(sorted))*proportion)) - 1
|
||||
if index < 0 {
|
||||
index = 0
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
return round(sorted[index], 3)
|
||||
}
|
||||
|
||||
func round(value float64, places int) float64 {
|
||||
shift := math.Pow10(places)
|
||||
return math.Round(value*shift) / shift
|
||||
}
|
||||
|
||||
func sampleMemory(stop <-chan struct{}, initial int, result chan<- memoryResult) {
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
peak := initial
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
result <- memoryResult{peak: peak}
|
||||
return
|
||||
case <-ticker.C:
|
||||
rss, err := rssKiB()
|
||||
if err != nil {
|
||||
result <- memoryResult{err: err}
|
||||
return
|
||||
}
|
||||
peak = max(peak, rss)
|
||||
}
|
||||
e = json.NewDecoder(resp.Body).Decode(&session)
|
||||
resp.Body.Close()
|
||||
if e != nil || resp.StatusCode != 201 || session.Token == "" {
|
||||
return "", fmt.Errorf("login status %d: %v", resp.StatusCode, e)
|
||||
}
|
||||
}
|
||||
|
||||
func runCase(image string, history, concurrency, repetition int, duration time.Duration) (runResult, error) {
|
||||
row := runResult{History: history, Concurrency: concurrency, Repetition: repetition}
|
||||
if _, err := docker("run", "-d", "--name", container, "--cpus=1", "--memory=512m",
|
||||
"-p", "127.0.0.1:18093:8080", image); err != nil {
|
||||
return row, err
|
||||
c.token = session.Token
|
||||
chat, _, e := c.call("POST", "/api/v1/chats", map[string]any{"title": "Benchmark", "member_ids": []any{user["id"]}}, "")
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
defer func() { _, _ = docker("rm", "-f", container) }()
|
||||
|
||||
setup := newClient(2 * time.Second)
|
||||
defer setup.CloseIdleConnections()
|
||||
readyDeadline := time.Now().Add(20 * time.Second)
|
||||
for {
|
||||
if _, err := request(setup, http.MethodGet, "/health/ready", "", nil); err == nil {
|
||||
break
|
||||
} else if time.Now().After(readyDeadline) {
|
||||
return row, fmt.Errorf("server did not become ready: %w", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
userResponse, err := request(setup, http.MethodPost, "/api/v1/users", "", map[string]any{
|
||||
"username": fmt.Sprintf("bench_%d_%d_%d", time.Now().UnixNano(), history, repetition),
|
||||
"display_name": "Benchmark",
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
user, err := stringField(userResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chatResponse, err := request(setup, http.MethodPost, "/api/v1/chats", user, map[string]any{
|
||||
"title": "Benchmark", "member_ids": []string{user},
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chat, err := stringField(chatResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
for index := range history {
|
||||
if _, err := request(setup, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("seed-%d", index),
|
||||
}); err != nil {
|
||||
return row, fmt.Errorf("seed message %d: %w", index, err)
|
||||
}
|
||||
}
|
||||
row.RSSBeforeKiB, err = rssKiB()
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan workerResult, concurrency)
|
||||
stopSampling := make(chan struct{})
|
||||
memory := make(chan memoryResult, 1)
|
||||
go sampleMemory(stopSampling, row.RSSBeforeKiB, memory)
|
||||
path := "/api/v1/chats/" + chat["id"].(string) + "/messages"
|
||||
// Bounded concurrent setup is excluded from the measured interval.
|
||||
var group sync.WaitGroup
|
||||
group.Add(concurrency)
|
||||
deadline := time.Now().Add(duration)
|
||||
started := time.Now()
|
||||
for workerID := range concurrency {
|
||||
go func() {
|
||||
defer group.Done()
|
||||
local := newClient(5 * time.Second)
|
||||
defer local.CloseIdleConnections()
|
||||
result := workerResult{}
|
||||
<-start
|
||||
for index := 0; time.Now().Before(deadline); index++ {
|
||||
began := time.Now()
|
||||
var err error
|
||||
if index%10 == 0 {
|
||||
_, err = request(local, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("load-%d-%d-%d", repetition, workerID, index),
|
||||
})
|
||||
if err == nil {
|
||||
result.writes++
|
||||
}
|
||||
} else {
|
||||
var page map[string]any
|
||||
page, err = request(local, http.MethodGet, path+"?limit=50", user, nil)
|
||||
if err == nil {
|
||||
items, ok := page["items"].([]any)
|
||||
if !ok || len(items) != 50 {
|
||||
err = errors.New("short first page")
|
||||
} else {
|
||||
result.reads++
|
||||
slots := make(chan struct{}, 8)
|
||||
errs := make(chan error, seed)
|
||||
for i := range seed {
|
||||
slots <- struct{}{}
|
||||
group.Go(func() {
|
||||
defer func() { <-slots }()
|
||||
_, _, e := c.call("POST", path, map[string]string{"text": fmt.Sprintf("seed-%d", i)}, uuid.NewString())
|
||||
if e != nil {
|
||||
errs <- e
|
||||
}
|
||||
})
|
||||
}
|
||||
group.Wait()
|
||||
close(errs)
|
||||
for e := range errs {
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
type result struct {
|
||||
MeasurementUnix float64 `json:"measurement_started_unix"`
|
||||
Label string `json:"label"`
|
||||
TargetRate int `json:"target_rps"`
|
||||
Duration float64 `json:"duration_seconds"`
|
||||
Elapsed float64 `json:"elapsed_including_drain_seconds"`
|
||||
Scheduled int `json:"scheduled"`
|
||||
Dropped int `json:"generator_dropped"`
|
||||
Success int `json:"successful_requests"`
|
||||
Errors int `json:"failed_requests"`
|
||||
ReadSuccess int `json:"read_success"`
|
||||
WriteSuccess int `json:"write_success"`
|
||||
SuccessfulRPS float64 `json:"successful_rps"`
|
||||
ErrorRatio float64 `json:"error_ratio_including_drops"`
|
||||
Latency map[string]float64 `json:"successful_latency_ms"`
|
||||
Statuses map[int]int `json:"statuses"`
|
||||
PeakInFlight int64 `json:"peak_in_flight"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
func phase(c *client, path string, rate int, duration time.Duration, maxInFlight int, label string) result {
|
||||
out := result{Label: label, TargetRate: rate, Duration: duration.Seconds(), Statuses: map[int]int{}, Latency: map[string]float64{}, Note: "Paced open-loop, 10ms dispatch batches; 90% first-page GET, 10% POST; no POST retries. Percentiles of successes include scheduler delay; failures and capacity drops reported separately. RPS denominator includes drain."}
|
||||
start := time.Now()
|
||||
out.MeasurementUnix = float64(start.UnixNano()) / 1e9
|
||||
end := start.Add(duration)
|
||||
slots := make(chan struct{}, maxInFlight)
|
||||
var group sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var active atomic.Int64
|
||||
var peak atomic.Int64
|
||||
latencies := make([]float64, 0, rate*int(duration.Seconds()))
|
||||
index := 0
|
||||
for tick := 0; ; tick++ {
|
||||
now := time.Now()
|
||||
if !now.Before(end) {
|
||||
break
|
||||
}
|
||||
target := start.Add(time.Duration(tick) * 10 * time.Millisecond)
|
||||
if target.After(now) {
|
||||
time.Sleep(time.Until(target))
|
||||
}
|
||||
until := min(int(time.Since(start).Seconds()*float64(rate))+1, int(duration.Seconds()*float64(rate)))
|
||||
for index < until {
|
||||
i := index
|
||||
index++
|
||||
out.Scheduled++
|
||||
scheduled := start.Add(time.Duration(float64(i) / float64(rate) * float64(time.Second)))
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
group.Go(func() {
|
||||
n := active.Add(1)
|
||||
for old := peak.Load(); n > old; old = peak.Load() {
|
||||
if peak.CompareAndSwap(old, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
result.errors++
|
||||
} else {
|
||||
result.latencies = append(result.latencies, float64(time.Since(began).Microseconds())/1000)
|
||||
}
|
||||
defer func() { active.Add(-1); <-slots }()
|
||||
method, p := "GET", path+"?limit=50"
|
||||
var body any
|
||||
key := ""
|
||||
if i%10 == 0 {
|
||||
method = "POST"
|
||||
p = path
|
||||
key = uuid.NewString()
|
||||
body = map[string]string{"text": key}
|
||||
}
|
||||
_, status, err := c.call(method, p, body, key)
|
||||
latency := float64(time.Since(scheduled).Microseconds()) / 1000
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
out.Statuses[status]++
|
||||
if err != nil {
|
||||
out.Errors++
|
||||
} else {
|
||||
out.Success++
|
||||
if method == "GET" {
|
||||
out.ReadSuccess++
|
||||
} else {
|
||||
out.WriteSuccess++
|
||||
}
|
||||
latencies = append(latencies, max(0, latency))
|
||||
}
|
||||
})
|
||||
default:
|
||||
out.Dropped++
|
||||
}
|
||||
results <- result
|
||||
}()
|
||||
}
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
row.ElapsedSeconds = round(time.Since(started).Seconds(), 3)
|
||||
close(stopSampling)
|
||||
memorySample := <-memory
|
||||
if memorySample.err != nil {
|
||||
return row, memorySample.err
|
||||
}
|
||||
row.RSSPeakKiB = memorySample.peak
|
||||
if finalRSS, err := rssKiB(); err == nil {
|
||||
row.RSSPeakKiB = max(row.RSSPeakKiB, finalRSS)
|
||||
} else {
|
||||
return row, err
|
||||
}
|
||||
latencies := make([]float64, 0)
|
||||
for range concurrency {
|
||||
result := <-results
|
||||
row.ReadSuccess += result.reads
|
||||
row.WriteSuccess += result.writes
|
||||
row.Errors += result.errors
|
||||
latencies = append(latencies, result.latencies...)
|
||||
}
|
||||
if len(latencies) == 0 {
|
||||
return row, errors.New("no successful requests")
|
||||
out.Elapsed = time.Since(start).Seconds()
|
||||
out.PeakInFlight = peak.Load()
|
||||
out.SuccessfulRPS = float64(out.Success) / out.Elapsed
|
||||
if out.Scheduled > 0 {
|
||||
out.ErrorRatio = float64(out.Errors+out.Dropped) / float64(out.Scheduled)
|
||||
}
|
||||
slices.Sort(latencies)
|
||||
row.SuccessfulRPS = round(float64(len(latencies))/row.ElapsedSeconds, 2)
|
||||
row.LatencyMS = map[string]float64{
|
||||
"p95": percentile(latencies, 0.95),
|
||||
"p99": percentile(latencies, 0.99),
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func parseValues(raw string, minimum int) ([]int, error) {
|
||||
values := make([]int, 0)
|
||||
for part := range strings.SplitSeq(raw, ",") {
|
||||
value, err := strconv.Atoi(strings.TrimSpace(part))
|
||||
if err != nil || value < minimum {
|
||||
return nil, fmt.Errorf("invalid value %q", part)
|
||||
for name, p := range map[string]float64{"p50": .5, "p95": .95, "p99": .99} {
|
||||
if len(latencies) > 0 {
|
||||
out.Latency[name] = latencies[max(0, int(math.Ceil(p*float64(len(latencies))))-1)]
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, nil
|
||||
return out
|
||||
}
|
||||
|
||||
func save(path string, data report) error {
|
||||
encoded, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(encoded, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func main() {
|
||||
image := flag.String("image", "", "Docker image to benchmark")
|
||||
output := flag.String("output", "", "JSON output path")
|
||||
historiesArg := flag.String("histories", "100,500,1500", "Comma-separated history sizes")
|
||||
concurrenciesArg := flag.String("concurrencies", "1,4,10", "Comma-separated client counts")
|
||||
repeats := flag.Int("repeats", 3, "Runs per combination")
|
||||
duration := flag.Duration("duration", 5*time.Second, "Measured duration per run")
|
||||
base := flag.String("base-url", "http://localhost:18080", "public LB URL")
|
||||
rate := flag.Int("rate", 100, "scheduled requests per second")
|
||||
duration := flag.Duration("duration", 30*time.Second, "measured time")
|
||||
warmup := flag.Duration("warmup", 5*time.Second, "warmup excluded from results")
|
||||
seed := flag.Int("seed", 1000, "initial messages")
|
||||
maxFlight := flag.Int("max-in-flight", 256, "bounded in-flight limit")
|
||||
label := flag.String("label", "manual", "case label")
|
||||
output := flag.String("output", "", "JSON destination")
|
||||
flag.Parse()
|
||||
if *image == "" || *output == "" || *repeats < 1 || *duration <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "image, output, positive repeats and duration are required")
|
||||
if *rate < 1 || *rate > 100000 || *duration <= 0 || *warmup < 0 || *maxFlight < 1 || *seed < 0 {
|
||||
fmt.Fprintln(os.Stderr, "invalid benchmark settings")
|
||||
os.Exit(2)
|
||||
}
|
||||
histories, err := parseValues(*historiesArg, 50)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
c := &client{base: *base, http: &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{MaxIdleConns: 512, MaxIdleConnsPerHost: 512, MaxConnsPerHost: *maxFlight, IdleConnTimeout: 60 * time.Second}}}
|
||||
path, e := c.setup(*seed)
|
||||
if e != nil {
|
||||
fmt.Fprintln(os.Stderr, "setup:", e)
|
||||
os.Exit(1)
|
||||
}
|
||||
concurrencies, err := parseValues(*concurrenciesArg, 1)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
if *warmup > 0 {
|
||||
phase(c, path, *rate, *warmup, *maxFlight, "warmup")
|
||||
}
|
||||
data := report{
|
||||
Image: *image,
|
||||
Method: map[string]any{
|
||||
"histories": histories, "concurrencies": concurrencies,
|
||||
"repeats": *repeats, "duration_seconds": duration.Seconds(),
|
||||
"mix": "90% first-page GET, 10% POST per client; persistent HTTP connections",
|
||||
"limits": "1 CPU, 512 MiB; fresh container and history per case",
|
||||
"rss": "VmRSS from /proc/1/status every 250 ms (sampled peak)",
|
||||
"latency": "successful requests only; errors counted separately; closed-loop workload",
|
||||
},
|
||||
Runs: make([]runResult, 0, len(histories)*len(concurrencies)*(*repeats)),
|
||||
row := phase(c, path, *rate, *duration, *maxFlight, *label)
|
||||
b, e := json.MarshalIndent(row, "", " ")
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
for _, history := range histories {
|
||||
for _, concurrency := range concurrencies {
|
||||
for repetition := 1; repetition <= *repeats; repetition++ {
|
||||
row, err := runCase(*image, history, concurrency, repetition, *duration)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
data.Runs = append(data.Runs, row)
|
||||
if err := save(*output, data); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
encoded, _ := json.Marshal(row)
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
if *output != "" {
|
||||
if e = os.WriteFile(*output, append(b, '\n'), 0644); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
fmt.Println(string(b))
|
||||
if row.Success == 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLostPostResponseIsNotRetried(t *testing.T) {
|
||||
var posts atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
return
|
||||
}
|
||||
posts.Add(1)
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
conn, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}))
|
||||
defer server.Close()
|
||||
transport := &http.Transport{MaxIdleConnsPerHost: 1}
|
||||
defer transport.CloseIdleConnections()
|
||||
c := &client{base: server.URL, http: &http.Client{Timeout: time.Second, Transport: transport}}
|
||||
if _, _, err := c.call(http.MethodGet, "/warm", nil, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := c.call(http.MethodPost, "/message", map[string]string{"text": "uncertain result"}, "same-key"); err == nil {
|
||||
t.Fatal("lost response must be reported as an error")
|
||||
}
|
||||
if posts.Load() != 1 {
|
||||
t.Fatalf("transport sent %d POSTs, want exactly 1", posts.Load())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user