Добавить генератор нагрузки, сбор метрик реплик и сценарии экспериментов для отказов, rolling update и трека 1
This commit is contained in:
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
// client is a minimal typed HTTP client for the messenger API.
|
||||
@@ -50,6 +52,40 @@ func (c *client) postMessage(chatID, token, text string, out any) error {
|
||||
return c.do(req, token, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
// sendWithKey sends one attempt of a message under the given key on a
|
||||
// connection of its own and reports the status, the message (on 201) and the
|
||||
// replica that answered.
|
||||
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)
|
||||
|
||||
+108
-9
@@ -1,12 +1,22 @@
|
||||
// Command concurrency is the black-box race check from the grading rubric:
|
||||
// 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.
|
||||
// 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, shared idempotency: in each of K rounds one user sends the same
|
||||
// message with the same Idempotency-Key P times in parallel, each attempt on
|
||||
// its own connection, so the balancer spreads them over the replicas. Every
|
||||
// attempt must answer 201 with the same message, the attempts must have
|
||||
// reached at least two replicas, the history must hold exactly K messages,
|
||||
// and the key with another text must answer 409.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -35,17 +45,37 @@ type Report struct {
|
||||
Ordered bool `json:"history_ordered_by_id"`
|
||||
Pages int `json:"pages_read"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
Passed bool `json:"passed"`
|
||||
// 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)
|
||||
report, err := run(*baseURL, *clients, *perClient, *rounds, *parallel, *requireReplicas)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
@@ -61,6 +91,8 @@ func main() {
|
||||
}
|
||||
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) {
|
||||
@@ -75,9 +107,9 @@ func writeReport(path string, text []byte) error {
|
||||
return os.WriteFile(path, append(text, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func run(baseURL string, clients, perClient int) (Report, error) {
|
||||
if clients < 1 || perClient < 1 {
|
||||
return Report{}, fmt.Errorf("clients and per-client must be positive")
|
||||
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,
|
||||
@@ -112,15 +144,82 @@ func run(baseURL string, clients, perClient int) (Report, error) {
|
||||
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.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"
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestRunAgainstLiveServer(t *testing.T) {
|
||||
srv := httptest.NewServer(a.Engine)
|
||||
defer srv.Close()
|
||||
|
||||
report, err := run(srv.URL, 10, 10)
|
||||
report, err := run(srv.URL, 10, 10, 5, 4, false)
|
||||
if err != nil {
|
||||
t.Fatalf("run error: %v", err)
|
||||
}
|
||||
@@ -56,10 +56,34 @@ func TestRunAgainstLiveServer(t *testing.T) {
|
||||
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); err == nil {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user