Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
// result is one HTTP exchange; instance is the X-Instance-Id of the answer,
|
||||
// empty when the balancer answered itself or nothing answered.
|
||||
type result struct {
|
||||
status int
|
||||
instance string
|
||||
body []byte
|
||||
latency time.Duration
|
||||
err error
|
||||
}
|
||||
|
||||
type client struct {
|
||||
base string
|
||||
http *http.Client
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// newClient keeps many connections open to the balancer, as many concurrent
|
||||
// users would; HAProxy balances every request, not every connection.
|
||||
func newClient(base string, timeout time.Duration) *client {
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: 10000,
|
||||
MaxIdleConnsPerHost: 10000,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
DisableCompression: true,
|
||||
}
|
||||
return &client{base: base, http: &http.Client{Transport: transport}, timeout: timeout}
|
||||
}
|
||||
|
||||
func (c *client) do(ctx context.Context, method, path, token, key string, body []byte, basic string) result {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
reader = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base+path, reader)
|
||||
if err != nil {
|
||||
return result{err: err}
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
switch {
|
||||
case basic != "":
|
||||
req.Header.Set("Authorization", "Basic "+basic)
|
||||
case token != "":
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
start := time.Now()
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return result{err: err, latency: time.Since(start)}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
r := result{status: resp.StatusCode, instance: resp.Header.Get("X-Instance-Id"), body: payload, latency: time.Since(start), err: err}
|
||||
return r
|
||||
}
|
||||
|
||||
func (c *client) postJSON(ctx context.Context, path, token, key string, body any) result {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return result{err: err}
|
||||
}
|
||||
return c.do(ctx, http.MethodPost, path, token, key, raw, "")
|
||||
}
|
||||
|
||||
// expect decodes the body of a result with the wanted status.
|
||||
func expect(r result, want int, out any) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
if r.status != want {
|
||||
return fmt.Errorf("status %d, want %d: %s", r.status, want, r.body)
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(r.body, out)
|
||||
}
|
||||
|
||||
func (c *client) register(ctx context.Context, username, password string) (string, error) {
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
body := map[string]string{"username": username, "display_name": username, "password": password}
|
||||
err := expect(c.postJSON(ctx, "/api/v1/users", "", "", body), http.StatusCreated, &created)
|
||||
return created.ID, err
|
||||
}
|
||||
|
||||
func (c *client) login(ctx context.Context, username, password string) (string, error) {
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
basic := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
err := expect(c.do(ctx, http.MethodPost, "/api/v1/auth/sessions", "", "", nil, basic), http.StatusCreated, &session)
|
||||
return session.Token, err
|
||||
}
|
||||
|
||||
func (c *client) createChat(ctx context.Context, token, title string, members []string) (string, error) {
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
body := map[string]any{"title": title, "member_ids": members}
|
||||
err := expect(c.postJSON(ctx, "/api/v1/chats", token, "", body), http.StatusCreated, &created)
|
||||
return created.ID, err
|
||||
}
|
||||
|
||||
func (c *client) send(ctx context.Context, chatID, token, key, text string) result {
|
||||
return c.postJSON(ctx, "/api/v1/chats/"+chatID+"/messages", token, key, map[string]string{"text": text})
|
||||
}
|
||||
|
||||
// firstPage reads the oldest page of a history: the read of the profile.
|
||||
func (c *client) firstPage(ctx context.Context, chatID, token string) result {
|
||||
return c.do(ctx, http.MethodGet, "/api/v1/chats/"+chatID+"/messages?limit=50", token, "", nil, "")
|
||||
}
|
||||
|
||||
type message struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// history reads a whole chat, page by page.
|
||||
func (c *client) history(ctx context.Context, chatID, token string) ([]message, error) {
|
||||
var all []message
|
||||
path := "/api/v1/chats/" + chatID + "/messages?limit=100"
|
||||
for range 100000 {
|
||||
var page struct {
|
||||
Items []message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
if err := expect(c.do(ctx, http.MethodGet, path, token, "", nil, ""), http.StatusOK, &page); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, page.Items...)
|
||||
if page.NextCursor == nil {
|
||||
return all, nil
|
||||
}
|
||||
path = "/api/v1/chats/" + chatID + "/messages?limit=100&cursor=" + url.QueryEscape(*page.NextCursor)
|
||||
}
|
||||
return nil, fmt.Errorf("history of %s did not end", chatID)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// Command loadgen is the open-loop load generator of the experiments.
|
||||
//
|
||||
// loadgen bench — seeds data, warms up, then offers each rate of -rates
|
||||
// for -step as a mix of history reads and message sends.
|
||||
// loadgen timeline — one user sends messages at -rate, retrying uncertain
|
||||
// sends with the same Idempotency-Key, then reads the
|
||||
// history back: every confirmed message once.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
mrand "math/rand/v2"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Mode string `json:"mode"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Users int `json:"users"`
|
||||
Chats int `json:"chats"`
|
||||
SeedMessages int `json:"seed_messages_per_chat"`
|
||||
ReadRatio float64 `json:"read_ratio"`
|
||||
Rates []float64 `json:"rates"`
|
||||
Step string `json:"step"`
|
||||
Warmup string `json:"warmup"`
|
||||
Rate float64 `json:"rate"`
|
||||
Duration string `json:"duration"`
|
||||
Timeout string `json:"client_timeout"`
|
||||
Seed uint64 `json:"seed"`
|
||||
Scrape bool `json:"scrape"`
|
||||
StopOnFail bool `json:"stop_on_fail"`
|
||||
StatsURL string `json:"stats_url"`
|
||||
APIHost string `json:"api_host"`
|
||||
DebugPort string `json:"debug_port"`
|
||||
Out string `json:"-"`
|
||||
|
||||
step, warmup, duration, timeout time.Duration
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 || (os.Args[1] != "bench" && os.Args[1] != "timeline") {
|
||||
fmt.Fprintln(os.Stderr, "usage: loadgen bench|timeline [flags]; loadgen bench -h for the flags")
|
||||
os.Exit(2)
|
||||
}
|
||||
cfg, err := parse(os.Args[1], os.Args[2:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "loadgen:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if cfg.Mode == "bench" {
|
||||
err = runBench(ctx, cfg)
|
||||
} else {
|
||||
err = runTimeline(ctx, cfg)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "loadgen:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func parse(mode string, args []string) (config, error) {
|
||||
cfg := config{Mode: mode}
|
||||
fs := flag.NewFlagSet(mode, flag.ContinueOnError)
|
||||
rates := fs.String("rates", "200,400", "bench: offered requests per second of each step")
|
||||
fs.StringVar(&cfg.BaseURL, "base-url", "http://lb:8080", "entry point of the API")
|
||||
fs.IntVar(&cfg.Users, "users", 200, "bench: synthetic users")
|
||||
fs.IntVar(&cfg.Chats, "chats", 100, "bench: chats of 2-5 random members")
|
||||
fs.IntVar(&cfg.SeedMessages, "seed-messages", 50, "bench: messages written into each chat before measuring")
|
||||
fs.Float64Var(&cfg.ReadRatio, "read-ratio", 0.8, "bench: share of history reads; the rest are message sends")
|
||||
fs.StringVar(&cfg.Step, "step", "30s", "bench: duration of each step")
|
||||
fs.StringVar(&cfg.Warmup, "warmup", "30s", "bench: unmeasured warm-up at the first rate")
|
||||
fs.Float64Var(&cfg.Rate, "rate", 50, "timeline: messages per second")
|
||||
fs.StringVar(&cfg.Duration, "duration", "60s", "timeline: duration")
|
||||
fs.StringVar(&cfg.Timeout, "timeout", "2s", "how long the generator waits for a response (class client_timeout)")
|
||||
fs.Uint64Var(&cfg.Seed, "seed", 1, "random seed of the request mix")
|
||||
fs.BoolVar(&cfg.StopOnFail, "stop-on-fail", false, "bench: end the ladder after the first step over 1 % errors or 500 ms p99")
|
||||
fs.BoolVar(&cfg.Scrape, "scrape", false, "sample HAProxy statistics and replica expvar every second")
|
||||
fs.StringVar(&cfg.StatsURL, "stats-url", "http://lb:8404/;csv", "HAProxy statistics CSV")
|
||||
fs.StringVar(&cfg.APIHost, "api-host", "api", "DNS name of the API replicas")
|
||||
fs.StringVar(&cfg.DebugPort, "debug-port", "9090", "internal expvar port of the replicas (APP_DEBUG_ADDR)")
|
||||
fs.StringVar(&cfg.Out, "out", "/out", "directory for the results")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
for _, part := range strings.Split(*rates, ",") {
|
||||
r, err := strconv.ParseFloat(strings.TrimSpace(part), 64)
|
||||
if err != nil || r <= 0 {
|
||||
return cfg, fmt.Errorf("rates: %q is not a positive number", part)
|
||||
}
|
||||
cfg.Rates = append(cfg.Rates, r)
|
||||
}
|
||||
for _, d := range []struct {
|
||||
name string
|
||||
raw string
|
||||
dst *time.Duration
|
||||
}{{"step", cfg.Step, &cfg.step}, {"warmup", cfg.Warmup, &cfg.warmup}, {"duration", cfg.Duration, &cfg.duration}, {"timeout", cfg.Timeout, &cfg.timeout}} {
|
||||
v, err := time.ParseDuration(d.raw)
|
||||
if err != nil || v < 0 {
|
||||
return cfg, fmt.Errorf("%s: %q is not a duration", d.name, d.raw)
|
||||
}
|
||||
*d.dst = v
|
||||
}
|
||||
if cfg.ReadRatio < 0 || cfg.ReadRatio > 1 || cfg.Rate <= 0 || cfg.step <= 0 || cfg.timeout <= 0 {
|
||||
return cfg, fmt.Errorf("read-ratio must be within 0..1; rate, step and timeout positive")
|
||||
}
|
||||
return cfg, os.MkdirAll(cfg.Out, 0o755)
|
||||
}
|
||||
|
||||
func writeJSON(path string, v any) error {
|
||||
raw, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(raw, '\n'), 0o644)
|
||||
}
|
||||
|
||||
// startScrape returns the function that stops the sampling and waits.
|
||||
func startScrape(ctx context.Context, cfg config, start time.Time) func() {
|
||||
if !cfg.Scrape {
|
||||
return func() {}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
s := scraper{statsURL: cfg.StatsURL, apiHost: cfg.APIHost, debugPort: cfg.DebugPort, http: &http.Client{}}
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() {
|
||||
if err := s.run(ctx, start, filepath.Join(cfg.Out, "metrics.jsonl")); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "loadgen: scrape:", err)
|
||||
}
|
||||
})
|
||||
return func() { cancel(); wg.Wait() }
|
||||
}
|
||||
|
||||
type benchReport struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
Config config `json:"config"`
|
||||
Users int `json:"users"`
|
||||
Chats int `json:"chats"`
|
||||
Seeded int `json:"seeded_messages"`
|
||||
Steps []stepSummary `json:"steps"`
|
||||
WritesOK int `json:"messages_written_during_steps"`
|
||||
}
|
||||
|
||||
func runBench(ctx context.Context, cfg config) error {
|
||||
c := newClient(cfg.BaseURL, cfg.timeout)
|
||||
rng := mrand.New(mrand.NewPCG(cfg.Seed, 0x6c6f6164))
|
||||
ds, err := seed(ctx, newClient(cfg.BaseURL, seedTimeout), rng, cfg.Users, cfg.Chats, cfg.SeedMessages)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
report := benchReport{StartedAt: time.Now().UTC(), Config: cfg, Users: len(ds.actors), Chats: len(ds.rooms), Seeded: ds.messages}
|
||||
start := time.Now()
|
||||
stopScrape := startScrape(ctx, cfg, start)
|
||||
defer stopScrape()
|
||||
|
||||
// next runs on the scheduling goroutine, which owns the random source.
|
||||
counter := 0
|
||||
next := func(rec *recorder) func(time.Time) func() {
|
||||
return func(planned time.Time) func() {
|
||||
r := ds.rooms[rng.IntN(len(ds.rooms))]
|
||||
a := ds.actors[r.members[rng.IntN(len(r.members))]]
|
||||
write := rng.Float64() >= cfg.ReadRatio
|
||||
counter++
|
||||
text := fmt.Sprintf("load %d", counter)
|
||||
return func() {
|
||||
sent := time.Now()
|
||||
var res result
|
||||
if write {
|
||||
res = c.send(ctx, r.id, a.token, uuid.NewString(), text)
|
||||
} else {
|
||||
res = c.firstPage(ctx, r.id, a.token)
|
||||
}
|
||||
rec.add(sample{planned: planned, lag: sent.Sub(planned), latency: res.latency, class: classify(res), instance: res.instance, write: write})
|
||||
}
|
||||
}
|
||||
}
|
||||
if cfg.warmup > 0 {
|
||||
openLoop(ctx, cfg.Rates[0], cfg.warmup, next(&recorder{}))
|
||||
}
|
||||
all := &recorder{}
|
||||
for _, rate := range cfg.Rates {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
stepStart := time.Now()
|
||||
rec := &recorder{}
|
||||
openLoop(ctx, rate, cfg.step, next(rec))
|
||||
s := summarize(rate, cfg.step, rec.all())
|
||||
s.StartedAt = stepStart.Sub(start).Seconds()
|
||||
report.Steps = append(report.Steps, s)
|
||||
report.WritesOK += s.Writes
|
||||
for _, x := range rec.all() {
|
||||
all.add(x)
|
||||
}
|
||||
fmt.Printf("step %6.0f rps: ok %7.1f rps, errors %5.2f%%, p99 %7.1f ms, lag p99 %5.1f ms, valid %v, passed %v\n",
|
||||
rate, s.OKRPS, 100*s.ErrorShare, s.P99Ms, s.LagP99Ms, s.Valid, s.Passed)
|
||||
if cfg.StopOnFail && s.overloaded() {
|
||||
break
|
||||
}
|
||||
}
|
||||
stopScrape()
|
||||
if err := os.WriteFile(filepath.Join(cfg.Out, "seconds.csv"), []byte(secondsCSV(start, all.all())), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeJSON(filepath.Join(cfg.Out, "steps.json"), report)
|
||||
}
|
||||
|
||||
type timelineReport struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
Config config `json:"config"`
|
||||
Jobs int `json:"messages_attempted"`
|
||||
Attempts int `json:"requests"`
|
||||
Confirmed int `json:"confirmed"`
|
||||
RetriedJobs int `json:"messages_retried"`
|
||||
Unresolved int `json:"unresolved"`
|
||||
Rejected int `json:"rejected_4xx"`
|
||||
Classes map[string]int `json:"classes"`
|
||||
Instances map[string]int `json:"instances"`
|
||||
History int `json:"history_messages"`
|
||||
Duplicates int `json:"duplicates"`
|
||||
Missing int `json:"missing_confirmed"`
|
||||
Passed bool `json:"passed"`
|
||||
}
|
||||
|
||||
// retryDelay spaces the attempts of one message whose outcome was uncertain.
|
||||
const retryDelay = 200 * time.Millisecond
|
||||
|
||||
// retryGrace bounds the retries of an uncertain message after the schedule ends.
|
||||
const retryGrace = 10 * time.Second
|
||||
|
||||
func runTimeline(ctx context.Context, cfg config) error {
|
||||
c := newClient(cfg.BaseURL, cfg.timeout)
|
||||
rng := mrand.New(mrand.NewPCG(cfg.Seed, 0x74696d65))
|
||||
ds, err := seed(ctx, newClient(cfg.BaseURL, seedTimeout), rng, 2, 1, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := ds.rooms[0]
|
||||
sender := ds.actors[r.members[0]]
|
||||
report := timelineReport{StartedAt: time.Now().UTC(), Config: cfg, Classes: map[string]int{}, Instances: map[string]int{}}
|
||||
runID := randomHex(3)
|
||||
start := time.Now()
|
||||
stopScrape := startScrape(ctx, cfg, start)
|
||||
defer stopScrape()
|
||||
deadline := start.Add(cfg.duration + retryGrace)
|
||||
|
||||
var mu sync.Mutex
|
||||
confirmed := map[string]string{} // text -> message id
|
||||
rec := &recorder{}
|
||||
jobs := 0
|
||||
openLoop(ctx, cfg.Rate, cfg.duration, func(planned time.Time) func() {
|
||||
jobs++
|
||||
key, text := uuid.NewString(), fmt.Sprintf("timeline %s %d", runID, jobs)
|
||||
return func() {
|
||||
for attempt := 0; ; attempt++ {
|
||||
sent := time.Now()
|
||||
res := c.send(ctx, r.id, sender.token, key, text)
|
||||
cls := classify(res)
|
||||
rec.add(sample{planned: planned, lag: sent.Sub(planned), latency: res.latency, class: cls, instance: res.instance, write: true})
|
||||
mu.Lock()
|
||||
switch {
|
||||
case cls == "ok":
|
||||
var m message
|
||||
if json.Unmarshal(res.body, &m) == nil {
|
||||
confirmed[text] = m.ID
|
||||
}
|
||||
case res.err == nil && res.status >= 400 && res.status < 500:
|
||||
report.Rejected++
|
||||
case time.Now().After(deadline) || ctx.Err() != nil:
|
||||
report.Unresolved++
|
||||
default:
|
||||
if attempt == 0 {
|
||||
report.RetriedJobs++
|
||||
}
|
||||
mu.Unlock()
|
||||
time.Sleep(retryDelay)
|
||||
planned = time.Now()
|
||||
continue
|
||||
}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
stopScrape()
|
||||
samples := rec.all()
|
||||
report.Jobs, report.Attempts, report.Confirmed = jobs, len(samples), len(confirmed)
|
||||
for _, x := range samples {
|
||||
report.Classes[x.class]++
|
||||
if x.instance != "" {
|
||||
report.Instances[x.instance]++
|
||||
}
|
||||
}
|
||||
|
||||
history, err := c.history(ctx, r.id, sender.token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read history back: %w", err)
|
||||
}
|
||||
report.History = len(history)
|
||||
seen := map[string]int{}
|
||||
byID := map[string]string{}
|
||||
for _, m := range history {
|
||||
seen[m.Text]++
|
||||
byID[m.ID] = m.Text
|
||||
}
|
||||
for _, n := range seen {
|
||||
if n > 1 {
|
||||
report.Duplicates += n - 1
|
||||
}
|
||||
}
|
||||
for text, id := range confirmed {
|
||||
if byID[id] != text {
|
||||
report.Missing++
|
||||
}
|
||||
}
|
||||
report.Passed = report.Duplicates == 0 && report.Missing == 0
|
||||
if err := os.WriteFile(filepath.Join(cfg.Out, "seconds.csv"), []byte(secondsCSV(start, samples)), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeJSON(filepath.Join(cfg.Out, "timeline.json"), report); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("timeline: %d messages, %d confirmed, %d retried, %d unresolved, %d duplicates, %d missing\n",
|
||||
report.Jobs, report.Confirmed, report.RetriedJobs, report.Unresolved, report.Duplicates, report.Missing)
|
||||
if !report.Passed {
|
||||
return fmt.Errorf("history check failed: %d duplicates, %d confirmed messages missing", report.Duplicates, report.Missing)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/app"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
var (
|
||||
db *testenv.DB
|
||||
kv *testenv.KV
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
var err error
|
||||
if db, err = testenv.StartPostgres(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if kv, err = testenv.StartValkey(ctx); err != nil {
|
||||
db.Close()
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
kv.Close()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func liveServer(t *testing.T) string {
|
||||
return serve(t, nil)
|
||||
}
|
||||
|
||||
func serve(t *testing.T, wrap func(http.Handler) http.Handler) string {
|
||||
t.Helper()
|
||||
a := app.New(app.Deps{
|
||||
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
DB: db.Pool,
|
||||
Sessions: kv.Client,
|
||||
SessionTTL: time.Hour,
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
InstanceID: "loadgen-test",
|
||||
})
|
||||
var h http.Handler = a.Engine
|
||||
if wrap != nil {
|
||||
h = wrap(h)
|
||||
}
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
// Registration hashes a password with Argon2id, which is slow on a small
|
||||
// replica; the setup is not measured, so it must not fail on the short
|
||||
// timeout of the measured requests.
|
||||
func TestSlowSetupDoesNotFailTheRun(t *testing.T) {
|
||||
slowAccounts := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && (r.URL.Path == "/api/v1/users" || r.URL.Path == "/api/v1/auth/sessions") {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
cfg, err := parse("bench", []string{"-base-url", serve(t, slowAccounts), "-users", "2", "-chats", "1", "-seed-messages", "1",
|
||||
"-rates", "10", "-step", "1s", "-warmup", "0s", "-timeout", "100ms", "-out", t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runBench(context.Background(), cfg); err != nil {
|
||||
t.Fatalf("a setup slower than -timeout failed the run: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBenchAgainstLiveServer(t *testing.T) {
|
||||
out := t.TempDir()
|
||||
cfg, err := parse("bench", []string{"-base-url", liveServer(t), "-users", "4", "-chats", "2", "-seed-messages", "3",
|
||||
"-rates", "20,40", "-step", "1s", "-warmup", "0s", "-out", out})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runBench(context.Background(), cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report benchReport
|
||||
raw, err := os.ReadFile(filepath.Join(out, "steps.json"))
|
||||
if err != nil || json.Unmarshal(raw, &report) != nil {
|
||||
t.Fatalf("steps.json: %v %s", err, raw)
|
||||
}
|
||||
if len(report.Steps) != 2 || report.Seeded != 6 || report.Users != 4 || report.Chats != 2 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
for _, s := range report.Steps {
|
||||
if s.Sent != int(s.OfferedRPS) || s.OK != s.Sent || s.ErrorShare != 0 || s.Instances["loadgen-test"] != s.Sent {
|
||||
t.Fatalf("step = %+v", s)
|
||||
}
|
||||
}
|
||||
csv, err := os.ReadFile(filepath.Join(out, "seconds.csv"))
|
||||
if err != nil || !strings.HasPrefix(string(csv), "second,sent,ok,") || strings.Count(string(csv), "\n") < 3 {
|
||||
t.Fatalf("seconds.csv: %v\n%s", err, csv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimelineVerifiesHistory(t *testing.T) {
|
||||
out := t.TempDir()
|
||||
cfg, err := parse("timeline", []string{"-base-url", liveServer(t), "-rate", "20", "-duration", "1s", "-out", out})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runTimeline(context.Background(), cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report timelineReport
|
||||
raw, err := os.ReadFile(filepath.Join(out, "timeline.json"))
|
||||
if err != nil || json.Unmarshal(raw, &report) != nil {
|
||||
t.Fatalf("timeline.json: %v %s", err, raw)
|
||||
}
|
||||
if report.Jobs != 20 || report.Confirmed != 20 || report.History != 20 || report.Duplicates != 0 || report.Missing != 0 || !report.Passed {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// openLoop sends request i at start + i/rate whatever the response times: a
|
||||
// closed loop would let a slow system lower its own load and hide its latency
|
||||
// (coordinated omission). It returns once every job has finished.
|
||||
func openLoop(ctx context.Context, rate float64, d time.Duration, next func(planned time.Time) func()) {
|
||||
n := int(rate * d.Seconds())
|
||||
interval := time.Duration(float64(time.Second) / rate)
|
||||
start := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
for i := range n {
|
||||
planned := start.Add(time.Duration(i) * interval)
|
||||
if wait := time.Until(planned); wait > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
wg.Go(next(planned))
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// recorder collects samples from concurrent jobs.
|
||||
type recorder struct {
|
||||
mu sync.Mutex
|
||||
samples []sample
|
||||
}
|
||||
|
||||
func (r *recorder) add(s sample) {
|
||||
r.mu.Lock()
|
||||
r.samples = append(r.samples, s)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *recorder) all() []sample {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]sample(nil), r.samples...)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// scraper samples the HAProxy statistics and every replica's expvar once a
|
||||
// second; replicas are found through Docker DNS, as HAProxy finds them.
|
||||
type scraper struct {
|
||||
statsURL string
|
||||
apiHost string
|
||||
debugPort string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
type scrapeLine struct {
|
||||
T float64 `json:"t"`
|
||||
HAProxy []map[string]string `json:"haproxy,omitempty"`
|
||||
Replicas []json.RawMessage `json:"replicas,omitempty"`
|
||||
}
|
||||
|
||||
// haproxyFields are the columns of the statistics CSV that are kept.
|
||||
var haproxyFields = []string{"svname", "status", "scur", "qcur", "stot", "rate", "rtime", "ttime", "hrsp_5xx", "chkfail", "econ", "eresp", "wretr", "wredis"}
|
||||
|
||||
func (s scraper) run(ctx context.Context, start time.Time, path string) error {
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
enc := json.NewEncoder(f)
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
}
|
||||
line := scrapeLine{T: time.Since(start).Seconds(), HAProxy: s.haproxy(ctx), Replicas: s.replicas(ctx)}
|
||||
if err := enc.Encode(line); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s scraper) get(ctx context.Context, url string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := s.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
}
|
||||
|
||||
// haproxy keeps the rows of the replicas backend.
|
||||
func (s scraper) haproxy(ctx context.Context) []map[string]string {
|
||||
raw, err := s.get(ctx, s.statsURL)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rows, err := csv.NewReader(strings.NewReader(strings.TrimPrefix(string(raw), "# "))).ReadAll()
|
||||
if err != nil || len(rows) < 2 {
|
||||
return nil
|
||||
}
|
||||
header := rows[0]
|
||||
col := map[string]int{}
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
var out []map[string]string
|
||||
for _, row := range rows[1:] {
|
||||
if len(row) != len(header) || row[col["pxname"]] != "replicas" || strings.HasPrefix(row[col["status"]], "MAINT") {
|
||||
continue
|
||||
}
|
||||
kept := map[string]string{}
|
||||
for _, name := range haproxyFields {
|
||||
if i, ok := col[name]; ok {
|
||||
kept[name] = row[i]
|
||||
}
|
||||
}
|
||||
out = append(out, kept)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// replicas returns the expvar documents of the running replicas, trimmed to
|
||||
// the fields the study uses.
|
||||
func (s scraper) replicas(ctx context.Context) []json.RawMessage {
|
||||
addrs, err := net.DefaultResolver.LookupHost(ctx, s.apiHost)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []json.RawMessage
|
||||
for _, addr := range addrs {
|
||||
raw, err := s.get(ctx, "http://"+net.JoinHostPort(addr, s.debugPort)+"/debug/vars")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var vars struct {
|
||||
Instance string `json:"instance"`
|
||||
GOMAXPROCS int `json:"gomaxprocs"`
|
||||
Pool json.RawMessage `json:"pgxpool"`
|
||||
Mem struct {
|
||||
HeapAlloc uint64 `json:"HeapAlloc"`
|
||||
Sys uint64 `json:"Sys"`
|
||||
NumGC uint32 `json:"NumGC"`
|
||||
PauseTotalNs uint64 `json:"PauseTotalNs"`
|
||||
GCCPUFraction float64 `json:"GCCPUFraction"`
|
||||
} `json:"memstats"`
|
||||
}
|
||||
if json.Unmarshal(raw, &vars) != nil {
|
||||
continue
|
||||
}
|
||||
kept, err := json.Marshal(map[string]any{
|
||||
"addr": addr, "instance": vars.Instance, "gomaxprocs": vars.GOMAXPROCS,
|
||||
"pgxpool": vars.Pool, "heap_alloc": vars.Mem.HeapAlloc, "sys": vars.Mem.Sys,
|
||||
"num_gc": vars.Mem.NumGC, "gc_pause_total_ns": vars.Mem.PauseTotalNs, "gc_cpu_fraction": vars.Mem.GCCPUFraction,
|
||||
})
|
||||
if err == nil {
|
||||
out = append(out, kept)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
mrand "math/rand/v2"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// seedPassword is shared by the synthetic users of one run.
|
||||
const seedPassword = "loadgen-synthetic-password"
|
||||
|
||||
// seedTimeout bounds one setup request. The setup is not measured, and
|
||||
// registration hashes a password with Argon2id, slow on a small replica.
|
||||
const seedTimeout = 30 * time.Second
|
||||
|
||||
// seedWorkers bounds the parallel registrations: each one hashes a password
|
||||
// with Argon2id, and the setup must not be what the study measures.
|
||||
const seedWorkers = 8
|
||||
|
||||
type actor struct {
|
||||
id, token string
|
||||
}
|
||||
|
||||
type room struct {
|
||||
id string
|
||||
members []int // indexes into dataset.actors
|
||||
}
|
||||
|
||||
type dataset struct {
|
||||
actors []actor
|
||||
rooms []room
|
||||
// messages is the number of messages written while seeding.
|
||||
messages int
|
||||
}
|
||||
|
||||
// seed registers users and logs each in once, creates chats of two to five
|
||||
// random members and writes perChat messages into each. Logins happen here,
|
||||
// so the password hashing never shows up in the measured steps.
|
||||
func seed(ctx context.Context, c *client, rng *mrand.Rand, users, chats, perChat int) (dataset, error) {
|
||||
if users < 2 || chats < 1 {
|
||||
return dataset{}, fmt.Errorf("need at least 2 users and 1 chat")
|
||||
}
|
||||
runID := randomHex(3)
|
||||
ds := dataset{actors: make([]actor, users)}
|
||||
if err := parallel(users, func(i int) error {
|
||||
name := fmt.Sprintf("lg_%s_%d", runID, i)
|
||||
id, err := c.register(ctx, name, seedPassword)
|
||||
if err != nil {
|
||||
return fmt.Errorf("register %s: %w", name, err)
|
||||
}
|
||||
token, err := c.login(ctx, name, seedPassword)
|
||||
if err != nil {
|
||||
return fmt.Errorf("log in %s: %w", name, err)
|
||||
}
|
||||
ds.actors[i] = actor{id: id, token: token}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return dataset{}, err
|
||||
}
|
||||
|
||||
for j := range chats {
|
||||
size := 2 + rng.IntN(4)
|
||||
members := rng.Perm(users)[:min(size, users)]
|
||||
ids := make([]string, len(members))
|
||||
for k, m := range members {
|
||||
ids[k] = ds.actors[m].id
|
||||
}
|
||||
id, err := c.createChat(ctx, ds.actors[members[0]].token, fmt.Sprintf("load %s %d", runID, j), ids)
|
||||
if err != nil {
|
||||
return dataset{}, fmt.Errorf("create chat %d: %w", j, err)
|
||||
}
|
||||
ds.rooms = append(ds.rooms, room{id: id, members: members})
|
||||
}
|
||||
|
||||
if err := parallel(len(ds.rooms), func(j int) error {
|
||||
r := ds.rooms[j]
|
||||
for k := range perChat {
|
||||
sender := ds.actors[r.members[k%len(r.members)]]
|
||||
res := c.send(ctx, r.id, sender.token, uuid.NewString(), fmt.Sprintf("seed %d", k))
|
||||
if err := expect(res, 201, nil); err != nil {
|
||||
return fmt.Errorf("seed message into chat %d: %w", j, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return dataset{}, err
|
||||
}
|
||||
ds.messages = len(ds.rooms) * perChat
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
// parallel runs fn(0..n-1) on seedWorkers goroutines and returns the first
|
||||
// error.
|
||||
func parallel(n int, fn func(i int) error) error {
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
first error
|
||||
)
|
||||
next := make(chan int)
|
||||
for range seedWorkers {
|
||||
wg.Go(func() {
|
||||
for i := range next {
|
||||
if err := fn(i); err != nil {
|
||||
mu.Lock()
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
for i := range n {
|
||||
next <- i
|
||||
}
|
||||
close(next)
|
||||
wg.Wait()
|
||||
return first
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxValidLag: if requests left later than this at p99, the generator, not
|
||||
// the system, limited the step.
|
||||
const maxValidLag = 10 * time.Millisecond
|
||||
|
||||
// The capacity criterion of the study: a step passes when it is valid, has
|
||||
// fewer than 1 % errors and its successful requests have a p99 within 500 ms.
|
||||
const (
|
||||
maxErrorShare = 0.01
|
||||
sloP99 = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
// sample is one request as the generator saw it.
|
||||
type sample struct {
|
||||
planned time.Time
|
||||
lag time.Duration // actual send time minus planned send time
|
||||
latency time.Duration
|
||||
class string
|
||||
instance string
|
||||
write bool
|
||||
}
|
||||
|
||||
// classify names the outcome of a request. Errors of the balancer itself carry
|
||||
// no X-Instance-Id and get the suffix _lb; client_timeout is the generator
|
||||
// giving up, not a timeout of the system.
|
||||
func classify(r result) string {
|
||||
switch {
|
||||
case r.err != nil && isTimeout(r.err):
|
||||
return "client_timeout"
|
||||
case r.err != nil:
|
||||
return "conn_error"
|
||||
case r.status >= 200 && r.status < 300:
|
||||
return "ok"
|
||||
case r.instance == "":
|
||||
return fmt.Sprintf("http_%d_lb", r.status)
|
||||
default:
|
||||
return fmt.Sprintf("http_%d", r.status)
|
||||
}
|
||||
}
|
||||
|
||||
func isTimeout(err error) bool {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return true
|
||||
}
|
||||
var netErr net.Error
|
||||
return errors.As(err, &netErr) && netErr.Timeout()
|
||||
}
|
||||
|
||||
// percentile is the nearest-rank percentile of an ascending slice.
|
||||
func percentile(sorted []time.Duration, p float64) time.Duration {
|
||||
if len(sorted) == 0 {
|
||||
return 0
|
||||
}
|
||||
rank := int(math.Ceil(p / 100 * float64(len(sorted))))
|
||||
return sorted[min(max(rank, 1), len(sorted))-1]
|
||||
}
|
||||
|
||||
type stepSummary struct {
|
||||
OfferedRPS float64 `json:"offered_rps"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
StartedAt float64 `json:"started_at_s"`
|
||||
Sent int `json:"sent"`
|
||||
OK int `json:"ok"`
|
||||
OKRPS float64 `json:"ok_rps"`
|
||||
ErrorShare float64 `json:"error_share"`
|
||||
Classes map[string]int `json:"classes"`
|
||||
P50Ms float64 `json:"ok_p50_ms"`
|
||||
P95Ms float64 `json:"ok_p95_ms"`
|
||||
P99Ms float64 `json:"ok_p99_ms"`
|
||||
LagP99Ms float64 `json:"lag_p99_ms"`
|
||||
Valid bool `json:"valid"`
|
||||
Passed bool `json:"passed"`
|
||||
Instances map[string]int `json:"instances"`
|
||||
Writes int `json:"writes_ok"`
|
||||
}
|
||||
|
||||
// summarize reduces one step; latency percentiles cover successful requests.
|
||||
func summarize(rate float64, d time.Duration, samples []sample) stepSummary {
|
||||
s := stepSummary{
|
||||
OfferedRPS: rate,
|
||||
Seconds: d.Seconds(),
|
||||
Sent: len(samples),
|
||||
Classes: map[string]int{},
|
||||
Instances: map[string]int{},
|
||||
}
|
||||
var ok, lags []time.Duration
|
||||
for _, x := range samples {
|
||||
s.Classes[x.class]++
|
||||
lags = append(lags, x.lag)
|
||||
if x.instance != "" {
|
||||
s.Instances[x.instance]++
|
||||
}
|
||||
if x.class == "ok" {
|
||||
ok = append(ok, x.latency)
|
||||
if x.write {
|
||||
s.Writes++
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(ok)
|
||||
slices.Sort(lags)
|
||||
s.OK = len(ok)
|
||||
s.OKRPS = float64(s.OK) / d.Seconds()
|
||||
if s.Sent > 0 {
|
||||
s.ErrorShare = float64(s.Sent-s.OK) / float64(s.Sent)
|
||||
}
|
||||
s.P50Ms, s.P95Ms, s.P99Ms = ms(percentile(ok, 50)), ms(percentile(ok, 95)), ms(percentile(ok, 99))
|
||||
lagP99 := percentile(lags, 99)
|
||||
s.LagP99Ms = ms(lagP99)
|
||||
s.Valid = lagP99 <= maxValidLag
|
||||
s.Passed = s.Valid && !s.overloaded()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s stepSummary) overloaded() bool {
|
||||
return s.ErrorShare >= maxErrorShare || s.P99Ms > ms(sloP99)
|
||||
}
|
||||
|
||||
func ms(d time.Duration) float64 {
|
||||
return float64(d.Microseconds()) / 1000
|
||||
}
|
||||
|
||||
// errorColumns are the fixed error columns of the per-second CSV; any other
|
||||
// class lands in err_other.
|
||||
var errorColumns = []string{"client_timeout", "conn_error"}
|
||||
|
||||
// secondsCSV renders the per-second timeline, attributed by planned send
|
||||
// time so it lines up with the moment a fault was injected.
|
||||
func secondsCSV(start time.Time, samples []sample) string {
|
||||
type bucket struct {
|
||||
samples []sample
|
||||
}
|
||||
buckets := map[int]*bucket{}
|
||||
last := 0
|
||||
for _, x := range samples {
|
||||
sec := int(x.planned.Sub(start) / time.Second)
|
||||
if buckets[sec] == nil {
|
||||
buckets[sec] = &bucket{}
|
||||
}
|
||||
buckets[sec].samples = append(buckets[sec].samples, x)
|
||||
last = max(last, sec)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("second,sent,ok,client_timeout,conn_error,http_5xx_api,http_5xx_lb,http_4xx,err_other,ok_p50_ms,ok_p95_ms,ok_p99_ms,lag_p99_ms,instances\n")
|
||||
for sec := 0; sec <= last; sec++ {
|
||||
bk := buckets[sec]
|
||||
if bk == nil {
|
||||
fmt.Fprintf(&b, "%d,0,0,0,0,0,0,0,0,0,0,0,0,\n", sec)
|
||||
continue
|
||||
}
|
||||
var ok, lags []time.Duration
|
||||
counts := map[string]int{}
|
||||
instances := map[string]int{}
|
||||
for _, x := range bk.samples {
|
||||
lags = append(lags, x.lag)
|
||||
if x.instance != "" {
|
||||
instances[x.instance]++
|
||||
}
|
||||
switch {
|
||||
case x.class == "ok":
|
||||
ok = append(ok, x.latency)
|
||||
case slices.Contains(errorColumns, x.class):
|
||||
counts[x.class]++
|
||||
case strings.HasPrefix(x.class, "http_5") && strings.HasSuffix(x.class, "_lb"):
|
||||
counts["http_5xx_lb"]++
|
||||
case strings.HasPrefix(x.class, "http_5"):
|
||||
counts["http_5xx_api"]++
|
||||
case strings.HasPrefix(x.class, "http_4"):
|
||||
counts["http_4xx"]++
|
||||
default:
|
||||
counts["err_other"]++
|
||||
}
|
||||
}
|
||||
slices.Sort(ok)
|
||||
slices.Sort(lags)
|
||||
names := make([]string, 0, len(instances))
|
||||
for name := range instances {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
parts := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
parts = append(parts, fmt.Sprintf("%s=%d", name, instances[name]))
|
||||
}
|
||||
fmt.Fprintf(&b, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%.1f,%.1f,%.1f,%.1f,%s\n",
|
||||
sec, len(bk.samples), len(ok),
|
||||
counts["client_timeout"], counts["conn_error"], counts["http_5xx_api"], counts["http_5xx_lb"], counts["http_4xx"], counts["err_other"],
|
||||
ms(percentile(ok, 50)), ms(percentile(ok, 95)), ms(percentile(ok, 99)), ms(percentile(lags, 99)),
|
||||
strings.Join(parts, "|"))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type timeoutErr struct{}
|
||||
|
||||
func (timeoutErr) Error() string { return "i/o timeout" }
|
||||
func (timeoutErr) Timeout() bool { return true }
|
||||
func (timeoutErr) Temporary() bool { return true }
|
||||
|
||||
var _ net.Error = timeoutErr{}
|
||||
|
||||
func TestClassify(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
res result
|
||||
want string
|
||||
}{
|
||||
{result{status: 201, instance: "a"}, "ok"},
|
||||
{result{status: 200, instance: "a"}, "ok"},
|
||||
{result{status: 409, instance: "a"}, "http_409"},
|
||||
{result{status: 503, instance: "a"}, "http_503"},
|
||||
{result{status: 503}, "http_503_lb"},
|
||||
{result{status: 502}, "http_502_lb"},
|
||||
{result{err: context.DeadlineExceeded}, "client_timeout"},
|
||||
{result{err: fmt.Errorf("post: %w", timeoutErr{})}, "client_timeout"},
|
||||
{result{err: errors.New("connection refused")}, "conn_error"},
|
||||
} {
|
||||
if got := classify(c.res); got != c.want {
|
||||
t.Errorf("classify(%+v) = %q, want %q", c.res, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPercentileNearestRank(t *testing.T) {
|
||||
ms := func(v ...int) []time.Duration {
|
||||
out := make([]time.Duration, len(v))
|
||||
for i, x := range v {
|
||||
out[i] = time.Duration(x) * time.Millisecond
|
||||
}
|
||||
return out
|
||||
}
|
||||
sorted := ms(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
for p, want := range map[float64]time.Duration{50: 5 * time.Millisecond, 95: 10 * time.Millisecond, 99: 10 * time.Millisecond, 10: time.Millisecond} {
|
||||
if got := percentile(sorted, p); got != want {
|
||||
t.Errorf("p%v = %v, want %v", p, got, want)
|
||||
}
|
||||
}
|
||||
if got := percentile(nil, 99); got != 0 {
|
||||
t.Errorf("empty p99 = %v, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A step is invalid when the generator itself fell behind its schedule: the
|
||||
// system was then offered less than the nominal rate.
|
||||
func TestStepSummaryValidityAndErrorShare(t *testing.T) {
|
||||
samples := []sample{
|
||||
{class: "ok", latency: 10 * time.Millisecond, lag: time.Millisecond},
|
||||
{class: "ok", latency: 20 * time.Millisecond, lag: time.Millisecond},
|
||||
{class: "client_timeout", latency: 2 * time.Second, lag: time.Millisecond},
|
||||
{class: "http_503_lb", latency: time.Millisecond, lag: time.Millisecond},
|
||||
}
|
||||
s := summarize(4, time.Second, samples)
|
||||
if s.Sent != 4 || s.OK != 2 || s.OKRPS != 2 || s.ErrorShare != 0.5 || !s.Valid {
|
||||
t.Fatalf("summary = %+v", s)
|
||||
}
|
||||
if s.Classes["client_timeout"] != 1 || s.Classes["http_503_lb"] != 1 {
|
||||
t.Fatalf("classes = %v", s.Classes)
|
||||
}
|
||||
if s.P99Ms != 20 {
|
||||
t.Fatalf("p99 of successful requests = %v ms, want 20", s.P99Ms)
|
||||
}
|
||||
samples[0].lag = 50 * time.Millisecond
|
||||
samples[1].lag = 50 * time.Millisecond
|
||||
if s := summarize(4, time.Second, samples); s.Valid {
|
||||
t.Fatalf("lagging generator marked valid: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// Open loop: requests leave on schedule even when responses are slow. A
|
||||
// closed loop with one worker would send only a handful here.
|
||||
func TestOpenLoopDoesNotWaitForResponses(t *testing.T) {
|
||||
var fired atomic.Int32
|
||||
start := time.Now()
|
||||
openLoop(context.Background(), 50, time.Second, func(time.Time) func() {
|
||||
return func() {
|
||||
fired.Add(1)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
})
|
||||
if n := fired.Load(); n < 45 || n > 50 {
|
||||
t.Fatalf("fired %d requests in 1 s at 50/s, want about 50", n)
|
||||
}
|
||||
// About 1.2 s; the bound leaves room for -race on a shared CI runner and
|
||||
// still fails a closed loop, which would need 50 x 200 ms = 10 s.
|
||||
if took := time.Since(start); took > 2500*time.Millisecond {
|
||||
t.Fatalf("open loop took %v, want about 1.2 s", took)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepPassesOnlyWithinTheObjective(t *testing.T) {
|
||||
ok := func(latency, lag time.Duration) sample {
|
||||
return sample{class: "ok", latency: latency, lag: lag}
|
||||
}
|
||||
fast := []sample{ok(10*time.Millisecond, time.Millisecond), ok(20*time.Millisecond, time.Millisecond)}
|
||||
if s := summarize(2, time.Second, fast); !s.Passed {
|
||||
t.Fatalf("fast clean step must pass: %+v", s)
|
||||
}
|
||||
slow := []sample{ok(10*time.Millisecond, time.Millisecond), ok(600*time.Millisecond, time.Millisecond)}
|
||||
if s := summarize(2, time.Second, slow); s.Passed {
|
||||
t.Fatalf("p99 above 500 ms must fail: %+v", s)
|
||||
}
|
||||
failing := append(fast, sample{class: "http_503_lb", lag: time.Millisecond})
|
||||
if s := summarize(3, time.Second, failing); s.Passed {
|
||||
t.Fatalf("errors above 1 %% must fail: %+v", s)
|
||||
}
|
||||
late := []sample{ok(10*time.Millisecond, 50*time.Millisecond), ok(10*time.Millisecond, 50*time.Millisecond)}
|
||||
if s := summarize(2, time.Second, late); s.Passed {
|
||||
t.Fatalf("an invalid step must fail: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// The ladder stops when the system leaves the objective, not when the
|
||||
// generator alone fell behind: a later step may still be valid and pass.
|
||||
func TestOnlyTheSystemEndsTheLadder(t *testing.T) {
|
||||
ok := func(latency, lag time.Duration) sample {
|
||||
return sample{class: "ok", latency: latency, lag: lag}
|
||||
}
|
||||
late := []sample{ok(10*time.Millisecond, 50*time.Millisecond), ok(10*time.Millisecond, 50*time.Millisecond)}
|
||||
if s := summarize(2, time.Second, late); s.overloaded() {
|
||||
t.Fatalf("a lagging generator must not end the ladder: %+v", s)
|
||||
}
|
||||
slow := []sample{ok(10*time.Millisecond, time.Millisecond), ok(600*time.Millisecond, time.Millisecond)}
|
||||
if s := summarize(2, time.Second, slow); !s.overloaded() {
|
||||
t.Fatalf("p99 above 500 ms must end the ladder: %+v", s)
|
||||
}
|
||||
failing := []sample{ok(10*time.Millisecond, time.Millisecond), {class: "client_timeout", lag: time.Millisecond}}
|
||||
if s := summarize(2, time.Second, failing); !s.overloaded() {
|
||||
t.Fatalf("errors above 1 %% must end the ladder: %+v", s)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user