Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
// client is a minimal typed HTTP client for the messenger API.
|
||||
type client struct {
|
||||
base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func newClient(baseURL string) *client {
|
||||
return &client{base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
|
||||
}
|
||||
|
||||
func (c *client) post(path, token string, body, out any) error {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return c.do(req, token, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
// postMessage sends one message under a fresh Idempotency-Key.
|
||||
func (c *client) postMessage(chatID, token, text string, out any) error {
|
||||
raw, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/chats/"+chatID+"/messages", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
return c.do(req, token, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
// sendWithKey sends one attempt on a connection of its own, so that the
|
||||
// attempts of one key reach different replicas.
|
||||
func (c *client) sendWithKey(chatID, token, key, text string) (int, chat.MessageResponse, string, error) {
|
||||
var msg chat.MessageResponse
|
||||
raw, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
return 0, msg, "", err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/chats/"+chatID+"/messages", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return 0, msg, "", err
|
||||
}
|
||||
req.Close = true
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return 0, msg, "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return 0, msg, "", err
|
||||
}
|
||||
if resp.StatusCode == http.StatusCreated {
|
||||
if err := json.Unmarshal(payload, &msg); err != nil {
|
||||
return 0, msg, "", err
|
||||
}
|
||||
}
|
||||
return resp.StatusCode, msg, resp.Header.Get("X-Instance-Id"), nil
|
||||
}
|
||||
|
||||
// login opens a session with Basic credentials and returns its bearer token.
|
||||
func (c *client) login(username, password string) (string, error) {
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.SetBasicAuth(username, password)
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.do(req, "", http.StatusCreated, &session); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return session.Token, nil
|
||||
}
|
||||
|
||||
// get requests the largest page the contract allows, continuing from cursor
|
||||
// when it is set.
|
||||
func (c *client) get(path, token, cursor string, out any) error {
|
||||
query := url.Values{"limit": {"100"}}
|
||||
if cursor != "" {
|
||||
query.Set("cursor", cursor)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, c.base+path+"?"+query.Encode(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.do(req, token, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (c *client) do(req *http.Request, token string, want int, out any) error {
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode != want {
|
||||
return fmt.Errorf("%s %s: status %d, want %d: %s", req.Method, req.URL.Path, resp.StatusCode, want, payload)
|
||||
}
|
||||
return json.Unmarshal(payload, out)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
// Command concurrency is the black-box race check from the grading rubric.
|
||||
//
|
||||
// Phase 1: N clients send M messages each into one chat at the same time,
|
||||
// then the history is paged and must contain exactly N*M unique messages in
|
||||
// id order.
|
||||
//
|
||||
// Phase 2: in each of K rounds one key is sent P times in parallel through the
|
||||
// balancer; every attempt must get 201 with one message, at least two replicas
|
||||
// must answer, the history must hold K messages, and another text must get 409.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/pagination"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
// Report is the machine readable outcome saved as evidence.
|
||||
type Report struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
Clients int `json:"clients"`
|
||||
PerClient int `json:"per_client"`
|
||||
Expected int `json:"expected_messages"`
|
||||
Created int `json:"created_201"`
|
||||
Failed int `json:"failed_posts"`
|
||||
Listed int `json:"listed_messages"`
|
||||
Unique int `json:"unique_ids"`
|
||||
Missing int `json:"created_but_not_listed"`
|
||||
Ordered bool `json:"history_ordered_by_id"`
|
||||
Pages int `json:"pages_read"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
// Idempotency is phase 2.
|
||||
Idempotency IdempotencyReport `json:"idempotency"`
|
||||
Passed bool `json:"passed"`
|
||||
}
|
||||
|
||||
type IdempotencyReport struct {
|
||||
Rounds int `json:"rounds"`
|
||||
Parallel int `json:"parallel"`
|
||||
// SameMessageRounds counts rounds whose attempts all answered 201 with
|
||||
// one and the same message.
|
||||
SameMessageRounds int `json:"same_message_rounds"`
|
||||
// InstancesSeen is the number of distinct X-Instance-Id values among all
|
||||
// attempts.
|
||||
InstancesSeen int `json:"instances_seen"`
|
||||
RequireReplicas bool `json:"require_two_replicas"`
|
||||
Conflict409 bool `json:"different_body_409"`
|
||||
History int `json:"history_messages"`
|
||||
Passed bool `json:"passed"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL")
|
||||
clients := flag.Int("clients", 10, "number of concurrent clients")
|
||||
perClient := flag.Int("per-client", 10, "messages sent by each client")
|
||||
rounds := flag.Int("rounds", 20, "idempotency rounds, one key each")
|
||||
parallel := flag.Int("parallel", 8, "parallel attempts with the same key per round")
|
||||
requireReplicas := flag.Bool("require-replicas", true, "fail unless the attempts reached at least two replicas")
|
||||
output := flag.String("output", "", "optional path for the JSON report")
|
||||
flag.Parse()
|
||||
|
||||
report, err := run(*baseURL, *clients, *perClient, *rounds, *parallel, *requireReplicas)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
text, _ := json.MarshalIndent(report, "", " ")
|
||||
fmt.Println(string(text))
|
||||
if *output != "" {
|
||||
if err := writeReport(*output, text); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
}
|
||||
if !report.Passed {
|
||||
fail(fmt.Errorf("concurrency invariants violated"))
|
||||
}
|
||||
fmt.Printf("PASS: %d clients x %d messages produced exactly %d unique ordered messages\n",
|
||||
report.Clients, report.PerClient, report.Unique)
|
||||
fmt.Printf("PASS: %d rounds x %d parallel attempts with one key produced %d messages across %d instances\n",
|
||||
report.Idempotency.Rounds, report.Idempotency.Parallel, report.Idempotency.History, report.Idempotency.InstancesSeen)
|
||||
}
|
||||
|
||||
func fail(err error) {
|
||||
fmt.Fprintln(os.Stderr, "FAIL:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func writeReport(path string, text []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(text, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func run(baseURL string, clients, perClient, rounds, parallel int, requireReplicas bool) (Report, error) {
|
||||
if clients < 2 || perClient < 1 || rounds < 1 || parallel < 1 {
|
||||
return Report{}, fmt.Errorf("clients must be at least 2; per-client, rounds and parallel positive")
|
||||
}
|
||||
report := Report{
|
||||
BaseURL: baseURL,
|
||||
StartedAt: time.Now().UTC(),
|
||||
Clients: clients,
|
||||
PerClient: perClient,
|
||||
Expected: clients * perClient,
|
||||
}
|
||||
api := newClient(baseURL)
|
||||
runID := uuid.NewString()[:8]
|
||||
|
||||
members, tokens, err := registerClients(api, runID, clients)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
room, err := createChat(api, runID, members, tokens[0])
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
created, failed := sendConcurrently(baseURL, room.ID, tokens, perClient)
|
||||
report.ElapsedSeconds = time.Since(started).Seconds()
|
||||
report.Created = len(created)
|
||||
report.Failed = failed
|
||||
|
||||
listed, pages, err := readHistory(api, room.ID, tokens[0])
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages = pages
|
||||
report.Listed = len(listed)
|
||||
report.Unique, report.Missing = compare(created, listed)
|
||||
report.Ordered = sort.StringsAreSorted(listed)
|
||||
report.Idempotency, err = checkIdempotency(api, baseURL, runID, members[:2], tokens[0], rounds, parallel, requireReplicas)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Passed = report.Failed == 0 &&
|
||||
report.Created == report.Expected &&
|
||||
report.Listed == report.Expected &&
|
||||
report.Unique == report.Expected &&
|
||||
report.Missing == 0 &&
|
||||
report.Ordered &&
|
||||
report.Idempotency.Passed
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// checkIdempotency runs phase 2 in a chat of its own.
|
||||
func checkIdempotency(api *client, baseURL, runID string, members []string, token string, rounds, parallel int, requireReplicas bool) (IdempotencyReport, error) {
|
||||
r := IdempotencyReport{Rounds: rounds, Parallel: parallel, RequireReplicas: requireReplicas}
|
||||
room, err := createChat(api, runID+"-idem", members, token)
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
instances := map[string]bool{}
|
||||
var key, text string
|
||||
for round := range rounds {
|
||||
key, text = uuid.NewString(), fmt.Sprintf("idempotency round %d", round)
|
||||
type attempt struct {
|
||||
status int
|
||||
id string
|
||||
instance string
|
||||
}
|
||||
attempts := make([]attempt, parallel)
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := range parallel {
|
||||
wg.Go(func() {
|
||||
own := newClient(baseURL)
|
||||
<-start
|
||||
status, msg, instance, err := own.sendWithKey(room.ID, token, key, text)
|
||||
if err == nil {
|
||||
attempts[i] = attempt{status, msg.ID, instance}
|
||||
}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
same := true
|
||||
for _, a := range attempts {
|
||||
if a.instance != "" {
|
||||
instances[a.instance] = true
|
||||
}
|
||||
if a.status != http.StatusCreated || a.id == "" || a.id != attempts[0].id {
|
||||
same = false
|
||||
}
|
||||
}
|
||||
if same {
|
||||
r.SameMessageRounds++
|
||||
}
|
||||
}
|
||||
r.InstancesSeen = len(instances)
|
||||
status, _, _, err := newClient(baseURL).sendWithKey(room.ID, token, key, text+" changed")
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
r.Conflict409 = status == http.StatusConflict
|
||||
listed, _, err := readHistory(api, room.ID, token)
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
r.History = len(listed)
|
||||
r.Passed = r.SameMessageRounds == rounds &&
|
||||
r.History == rounds &&
|
||||
r.Conflict409 &&
|
||||
(!requireReplicas || r.InstancesSeen >= 2)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// clientPassword is shared by the synthetic clients of one run.
|
||||
const clientPassword = "concurrency-check-password"
|
||||
|
||||
// registerClients registers and logs in n clients, returning their ids and
|
||||
// bearer tokens in the same order.
|
||||
func registerClients(api *client, runID string, n int) (ids, tokens []string, err error) {
|
||||
for i := range n {
|
||||
var created user.Response
|
||||
username := fmt.Sprintf("load_%s_%d", runID, i)
|
||||
body := map[string]string{
|
||||
"username": username,
|
||||
"display_name": fmt.Sprintf("Load client %d", i),
|
||||
"password": clientPassword,
|
||||
}
|
||||
if err := api.post("/api/v1/users", "", body, &created); err != nil {
|
||||
return nil, nil, fmt.Errorf("register client %d: %w", i, err)
|
||||
}
|
||||
token, err := api.login(username, clientPassword)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("log in client %d: %w", i, err)
|
||||
}
|
||||
ids = append(ids, created.ID)
|
||||
tokens = append(tokens, token)
|
||||
}
|
||||
return ids, tokens, nil
|
||||
}
|
||||
|
||||
func createChat(api *client, runID string, members []string, creatorToken string) (chat.ChatResponse, error) {
|
||||
var created chat.ChatResponse
|
||||
body := map[string]any{"title": "Concurrency check " + runID, "member_ids": members}
|
||||
if err := api.post("/api/v1/chats", creatorToken, body, &created); err != nil {
|
||||
return chat.ChatResponse{}, fmt.Errorf("create chat: %w", err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// sendConcurrently gives every member its own HTTP client and releases them
|
||||
// together, so the server sees genuinely parallel writes to one chat.
|
||||
func sendConcurrently(baseURL, chatID string, tokens []string, perClient int) (map[string]struct{}, int) {
|
||||
var mu sync.Mutex
|
||||
created := make(map[string]struct{}, len(tokens)*perClient)
|
||||
failed := 0
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i, token := range tokens {
|
||||
wg.Add(1)
|
||||
go func(n int, token string) {
|
||||
defer wg.Done()
|
||||
own := newClient(baseURL)
|
||||
<-start
|
||||
for m := range perClient {
|
||||
var msg chat.MessageResponse
|
||||
err := own.postMessage(chatID, token, fmt.Sprintf("client %d message %d", n, m), &msg)
|
||||
mu.Lock()
|
||||
if err != nil {
|
||||
failed++
|
||||
} else {
|
||||
created[msg.ID] = struct{}{}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}(i, token)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
return created, failed
|
||||
}
|
||||
|
||||
func readHistory(api *client, chatID, token string) ([]string, int, error) {
|
||||
var ids []string
|
||||
pages := 0
|
||||
cursor := ""
|
||||
for {
|
||||
var page pagination.PageResponse[chat.MessageResponse]
|
||||
if err := api.get("/api/v1/chats/"+chatID+"/messages", token, cursor, &page); err != nil {
|
||||
return nil, pages, fmt.Errorf("read history: %w", err)
|
||||
}
|
||||
pages++
|
||||
for _, m := range page.Items {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
return ids, pages, nil
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
}
|
||||
|
||||
// compare returns how many distinct ids the history holds and how many
|
||||
// acknowledged ids never showed up in it.
|
||||
func compare(created map[string]struct{}, listed []string) (unique, missing int) {
|
||||
seen := make(map[string]struct{}, len(listed))
|
||||
for _, id := range listed {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
for id := range created {
|
||||
if _, ok := seen[id]; !ok {
|
||||
missing++
|
||||
}
|
||||
}
|
||||
return len(seen), missing
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"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 TestRunAgainstLiveServer(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
a := app.New(app.Deps{Log: log, DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 64 * 1024, InstanceID: "concurrency-test"})
|
||||
srv := httptest.NewServer(a.Engine)
|
||||
defer srv.Close()
|
||||
|
||||
report, err := run(srv.URL, 10, 10, 5, 4, false)
|
||||
if err != nil {
|
||||
t.Fatalf("run error: %v", err)
|
||||
}
|
||||
if report.Clients != 10 || report.PerClient != 10 || report.Expected != 100 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
if report.Created != 100 || report.Listed != 100 || report.Unique != 100 || report.Missing != 0 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
if !report.Ordered || !report.Passed {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
idem := report.Idempotency
|
||||
if idem.Rounds != 5 || idem.Parallel != 4 || idem.SameMessageRounds != 5 || idem.History != 5 || !idem.Conflict409 || !idem.Passed {
|
||||
t.Fatalf("idempotency = %+v", idem)
|
||||
}
|
||||
if idem.InstancesSeen != 1 {
|
||||
t.Fatalf("one in-process server must be seen as one instance: %+v", idem)
|
||||
}
|
||||
}
|
||||
|
||||
// Through the balancer the same key must reach at least two replicas; one
|
||||
// replica alone does not prove the idempotency is shared.
|
||||
func TestIdempotencyRequiresTwoReplicasByDefault(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
a := app.New(app.Deps{Log: log, DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 64 * 1024, InstanceID: "concurrency-test"})
|
||||
srv := httptest.NewServer(a.Engine)
|
||||
defer srv.Close()
|
||||
|
||||
report, err := run(srv.URL, 2, 1, 2, 2, true)
|
||||
if err != nil {
|
||||
t.Fatalf("run error: %v", err)
|
||||
}
|
||||
if report.Idempotency.Passed || report.Passed {
|
||||
t.Fatalf("a single instance passed the shared idempotency check: %+v", report.Idempotency)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunFailsOnUnreachableServer(t *testing.T) {
|
||||
if _, err := run("http://127.0.0.1:1", 2, 2, 1, 1, false); err == nil {
|
||||
t.Fatal("expected an error for an unreachable server")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
// Command reconcilebench measures reconciliation against disposable real
|
||||
// PostgreSQL and S3 services, independently of the compose stand.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
o, err := parseOptions(os.Args[1:], os.Stderr)
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||
var records bytes.Buffer
|
||||
var resultOut io.Writer = os.Stdout
|
||||
if o.output != "" {
|
||||
resultOut = io.MultiWriter(os.Stdout, &records)
|
||||
}
|
||||
err = exercise(ctx, o, resultOut, os.Stderr)
|
||||
if o.output != "" {
|
||||
if saveErr := writeResults(o.output, records.Bytes()); saveErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("save results: %w", saveErr))
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
stop()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconcilebench:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func writeResults(path string, records []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(records))
|
||||
rows := make([]json.RawMessage, 0)
|
||||
for {
|
||||
var row json.RawMessage
|
||||
err := decoder.Decode(&row)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
raw, err := json.MarshalIndent(rows, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(raw, '\n'), 0644)
|
||||
}
|
||||
|
||||
type measurement struct {
|
||||
Phase string `json:"phase"`
|
||||
Mode string `json:"mode"`
|
||||
TargetFiles int `json:"target_files"`
|
||||
GoHeapPeakBytes uint64 `json:"go_heap_peak_bytes"`
|
||||
Stats attachment.Stats `json:"stats"`
|
||||
Findings []attachment.Finding `json:"findings,omitempty"`
|
||||
}
|
||||
|
||||
// Heap samples cover this Go process during Run. They exclude service processes
|
||||
// and are deliberately not described as process RSS or total deployment memory.
|
||||
func measure(ctx context.Context, r *attachment.Reconciler, phase, mode string, n int, apply, deep bool, out io.Writer) (attachment.Stats, error) {
|
||||
done := make(chan struct{})
|
||||
peakCh := make(chan uint64, 1)
|
||||
go func() {
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
peak := mem.HeapAlloc
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
runtime.ReadMemStats(&mem)
|
||||
if mem.HeapAlloc > peak {
|
||||
peak = mem.HeapAlloc
|
||||
}
|
||||
case <-done:
|
||||
runtime.ReadMemStats(&mem)
|
||||
if mem.HeapAlloc > peak {
|
||||
peak = mem.HeapAlloc
|
||||
}
|
||||
peakCh <- peak
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
m := measurement{Phase: phase, Mode: mode, TargetFiles: n}
|
||||
options := attachment.ReconcileOptions{Apply: apply, Deep: deep}
|
||||
stats, err := r.Run(ctx, options, func(f attachment.Finding) { m.Findings = append(m.Findings, f) })
|
||||
close(done)
|
||||
m.GoHeapPeakBytes = <-peakCh
|
||||
m.Stats = stats
|
||||
if writeErr := json.NewEncoder(out).Encode(m); writeErr != nil {
|
||||
return stats, writeErr
|
||||
}
|
||||
return stats, err
|
||||
}
|
||||
|
||||
func exercise(ctx context.Context, o options, out, progress io.Writer) error {
|
||||
db, err := testenv.StartPostgres(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
s3, err := testenv.StartS3(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s3.Close()
|
||||
if err = json.NewEncoder(out).Encode(map[string]any{
|
||||
"phase": "environment", "postgres_image": testenv.PostgresImage, "s3_image": testenv.S3Image,
|
||||
"grace_ms": o.grace.Milliseconds(), "wait_ms": o.wait.Milliseconds(),
|
||||
"memory_metric": "sampled Go process HeapAlloc bytes during Run; not RSS; excludes PostgreSQL and S3",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := seedFaults(ctx, db.Pool, s3.Store)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(progress, "fault objects seeded; waiting %s for real S3 timestamps to age\n", o.wait)
|
||||
if err = waitForAge(ctx, o.wait, progress); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.seedFresh(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := attachment.NewReconciler(db.Pool, s3.Store, o.grace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, run := range []struct {
|
||||
mode string
|
||||
apply bool
|
||||
repairs, findings int64
|
||||
}{{"dry", false, 0, 6}, {"apply", true, 5, 6}, {"repeat", true, 0, 1}} {
|
||||
stats, err := measure(ctx, r, "fault", run.mode, 7, run.apply, true, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if stats.Repaired != run.repairs || stats.Findings != run.findings {
|
||||
return fmt.Errorf("fault %s: wanted %d repairs/%d findings, got %+v", run.mode, run.repairs, run.findings, stats)
|
||||
}
|
||||
if err = f.assertState(ctx, run.apply); err != nil {
|
||||
return fmt.Errorf("fault %s: %w", run.mode, err)
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(progress, "fault dry/apply/repeat passed; referenced messages, corrupt used blobs and fresh objects preserved")
|
||||
// These resources were created above solely for this run; no compose
|
||||
// endpoint or pre-existing database/bucket is ever accepted by this tool.
|
||||
if _, err = db.Pool.Exec(ctx, `TRUNCATE message_attachments,attachments,files`); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = emptyBucket(ctx, s3.Store); err != nil {
|
||||
return err
|
||||
}
|
||||
seeded := 0
|
||||
for _, n := range o.sizes {
|
||||
for i := seeded; i < n; i++ {
|
||||
if err = seedScaleFile(ctx, db.Pool, s3.Store, f.user, f.chat, i); err != nil {
|
||||
return err
|
||||
}
|
||||
if (i+1)%500 == 0 {
|
||||
fmt.Fprintf(progress, "seeded %d referenced real objects\n", i+1)
|
||||
}
|
||||
}
|
||||
seeded = n
|
||||
stats, err := measure(ctx, r, "cost", "dry", n, false, false, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if stats.ScannedFiles != int64(n) || stats.ScannedObjects != int64(n) || stats.Findings != 0 || stats.Repaired != 0 {
|
||||
return fmt.Errorf("cost %d: inconsistent fixture %+v", n, stats)
|
||||
}
|
||||
}
|
||||
return json.NewEncoder(out).Encode(map[string]any{"phase": "complete", "fault_checks": "passed", "sizes": o.sizes})
|
||||
}
|
||||
|
||||
func waitForAge(ctx context.Context, d time.Duration, progress io.Writer) error {
|
||||
start := time.Now()
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
fmt.Fprintf(progress, "aging real S3 objects: %s / %s\n", time.Since(start).Round(time.Second), d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type benchFile struct {
|
||||
hash []byte
|
||||
before, after string
|
||||
}
|
||||
type benchObject struct {
|
||||
key string
|
||||
after bool
|
||||
}
|
||||
type faultFixture struct {
|
||||
db *pgxpool.Pool
|
||||
blobs attachment.Blobs
|
||||
user, chat uuid.UUID
|
||||
files []benchFile
|
||||
objects []benchObject
|
||||
}
|
||||
|
||||
func seedFaults(ctx context.Context, db *pgxpool.Pool, blobs attachment.Blobs) (*faultFixture, error) {
|
||||
f := &faultFixture{db: db, blobs: blobs, user: uuid.New(), chat: uuid.New()}
|
||||
if _, err := db.Exec(ctx, `INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,'bench','unused',now())`, f.user, "bench-"+f.user.String()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := db.Exec(ctx, `INSERT INTO chats(id,title,created_at) VALUES($1,'reconcilebench',now())`, f.chat); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := f.put(ctx, "staging/old", []byte("stale staging"), false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orphan := sha256.Sum256([]byte("old orphan"))
|
||||
if err := f.put(ctx, attachment.BlobKey(orphan[:]), []byte("old orphan"), false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range []struct {
|
||||
label, status, after string
|
||||
used, present, corrupt bool
|
||||
}{
|
||||
{"pending", "pending", "", false, true, false},
|
||||
{"unused", "ready", "", false, true, false},
|
||||
{"used", "ready", "ready", true, true, false},
|
||||
{"corrupt", "ready", "ready", true, true, true},
|
||||
{"missing", "ready", "failed", true, false, false},
|
||||
{"already_failed", "failed", "failed", true, false, false},
|
||||
} {
|
||||
if err := f.file(ctx, c.label, c.status, c.after, c.used, c.present, c.corrupt, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (f *faultFixture) put(ctx context.Context, key string, body []byte, keep bool) error {
|
||||
if err := f.blobs.Put(ctx, key, bytes.NewReader(body), int64(len(body)), "image/png"); err != nil {
|
||||
return err
|
||||
}
|
||||
f.objects = append(f.objects, benchObject{key: key, after: keep})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *faultFixture) file(ctx context.Context, label, status, after string, used, present, corrupt, fresh bool) error {
|
||||
body := []byte("fixture/" + label)
|
||||
hash := sha256.Sum256(body)
|
||||
created := time.Now().Add(-2 * time.Hour)
|
||||
if fresh {
|
||||
created = time.Now()
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png',$3,$4)`, hash[:], len(body), status, created); err != nil {
|
||||
return err
|
||||
}
|
||||
f.files = append(f.files, benchFile{hash: hash[:], before: status, after: after})
|
||||
if used {
|
||||
id, message := uuid.New(), uuid.New()
|
||||
if _, err := f.db.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'fixture.png',$4,now())`, id, f.chat, f.user, hash[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, `INSERT INTO messages(chat_id,id,sender_id,text,created_at) VALUES($1,$2,$3,'preserve',now())`, f.chat, message, f.user); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, `INSERT INTO message_attachments(chat_id,message_id,attachment_id,ordinal) VALUES($1,$2,$3,0)`, f.chat, message, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if present {
|
||||
if corrupt {
|
||||
body[0] ^= 1
|
||||
}
|
||||
return f.put(ctx, attachment.BlobKey(hash[:]), body, after != "")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *faultFixture) seedFresh(ctx context.Context) error {
|
||||
if err := f.put(ctx, "staging/fresh", []byte("fresh staging"), true); err != nil {
|
||||
return err
|
||||
}
|
||||
orphan := sha256.Sum256([]byte("fresh orphan"))
|
||||
if err := f.put(ctx, attachment.BlobKey(orphan[:]), []byte("fresh orphan"), true); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.file(ctx, "fresh pending", "pending", "pending", false, true, false, true)
|
||||
}
|
||||
|
||||
func (f *faultFixture) assertState(ctx context.Context, applied bool) error {
|
||||
for _, file := range f.files {
|
||||
var status string
|
||||
err := f.db.QueryRow(ctx, `SELECT status FROM files WHERE hash=$1`, file.hash).Scan(&status)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
want := file.before
|
||||
if applied {
|
||||
want = file.after
|
||||
}
|
||||
if status != want {
|
||||
return fmt.Errorf("file %s: status=%q, want %q", attachment.BlobKey(file.hash), status, want)
|
||||
}
|
||||
}
|
||||
for _, obj := range f.objects {
|
||||
_, err := f.blobs.Stat(ctx, obj.key)
|
||||
want := !applied || obj.after
|
||||
if err != nil && !errors.Is(err, attachment.ErrObjectMissing) {
|
||||
return err
|
||||
}
|
||||
if (err == nil) != want {
|
||||
return fmt.Errorf("object %s: present=%v want %v", obj.key, err == nil, want)
|
||||
}
|
||||
}
|
||||
var attachments, links int
|
||||
if err := f.db.QueryRow(ctx, `SELECT (SELECT count(*) FROM attachments),(SELECT count(*) FROM message_attachments)`).Scan(&attachments, &links); err != nil {
|
||||
return err
|
||||
}
|
||||
if attachments != 4 || links != 4 {
|
||||
return fmt.Errorf("referenced attachments/messages lost: %d/%d", attachments, links)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func emptyBucket(ctx context.Context, blobs attachment.Blobs) error {
|
||||
for {
|
||||
page, err := blobs.List(ctx, "", "", 500)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(page) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, obj := range page {
|
||||
if err := blobs.Delete(ctx, obj.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedScaleFile(ctx context.Context, db *pgxpool.Pool, blobs attachment.Blobs, user, chat uuid.UUID, i int) error {
|
||||
body := fmt.Sprintf("scale/%09d", i)
|
||||
hash := sha256.Sum256([]byte(body))
|
||||
if err := blobs.Put(ctx, attachment.BlobKey(hash[:]), strings.NewReader(body), int64(len(body)), "image/png"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := db.Exec(ctx, `WITH f AS (
|
||||
INSERT INTO files(hash,size_bytes,mime_type,status,created_at)
|
||||
VALUES($1,$2,'image/png','ready',now()-interval '2 hour') RETURNING hash)
|
||||
INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at)
|
||||
SELECT $3,$4,$5,'scale.png',hash,now() FROM f`, hash[:], len(body), uuid.New(), chat, user)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOptionsProtectRealAgingAndValidateSizes(t *testing.T) {
|
||||
got, err := parseOptions(nil, io.Discard)
|
||||
if err != nil || got.grace != 2*time.Minute || got.wait != 125*time.Second || !reflect.DeepEqual(got.sizes, []int{100, 1000, 5000}) {
|
||||
t.Fatalf("defaults: %+v %v", got, err)
|
||||
}
|
||||
for _, args := range [][]string{{"--grace=1m"}, {"--wait=2m"}, {"--sizes=0"}, {"--sizes=10,10"}, {"--sizes=10,5"}, {"--sizes=oops"}, {"extra"}} {
|
||||
if _, err := parseOptions(args, io.Discard); err == nil {
|
||||
t.Errorf("accepted unsafe options %v", args)
|
||||
}
|
||||
}
|
||||
got, err = parseOptions([]string{"--sizes=2,7", "--grace=3m", "--wait=3m2s"}, io.Discard)
|
||||
if err != nil || !reflect.DeepEqual(got.sizes, []int{2, 7}) {
|
||||
t.Fatalf("explicit options: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputOptionWritesStructuredJSON(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "track2", "results.json")
|
||||
o, err := parseOptions([]string{"--output", path}, io.Discard)
|
||||
if err != nil || o.output != path {
|
||||
t.Fatalf("output flag: %+v %v", o, err)
|
||||
}
|
||||
if err = writeResults(path, []byte("{\"phase\":\"fault\"}\n{\"phase\":\"complete\"}\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rows []map[string]any
|
||||
if err = json.Unmarshal(raw, &rows); err != nil || len(rows) != 2 || rows[1]["phase"] != "complete" {
|
||||
t.Fatalf("results JSON: %s %v", raw, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type options struct {
|
||||
grace, wait time.Duration
|
||||
sizes []int
|
||||
output string
|
||||
}
|
||||
|
||||
func parseOptions(args []string, out io.Writer) (options, error) {
|
||||
var o options
|
||||
f := flag.NewFlagSet("reconcilebench", flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
f.DurationVar(&o.grace, "grace", 2*time.Minute, "reconciler grace (minimum 2m)")
|
||||
f.DurationVar(&o.wait, "wait", 125*time.Second, "actual S3 aging wait (must exceed grace by at least 1s)")
|
||||
f.StringVar(&o.output, "output", "", "also save measurement records as a JSON array at this path")
|
||||
sizes := f.String("sizes", "100,1000,5000", "strictly increasing referenced object counts")
|
||||
if err := f.Parse(args); err != nil {
|
||||
return o, err
|
||||
}
|
||||
if f.NArg() != 0 || o.grace < 2*time.Minute || o.wait-o.grace < time.Second {
|
||||
return o, errors.New("no positional arguments; grace >= 2m and wait >= grace+1s required")
|
||||
}
|
||||
last := 0
|
||||
for _, raw := range strings.Split(*sizes, ",") {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil || n <= last {
|
||||
return o, fmt.Errorf("sizes must be strictly increasing positive integers: %q", raw)
|
||||
}
|
||||
o.sizes = append(o.sizes, n)
|
||||
last = n
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
Reference in New Issue
Block a user