Files
mtusi2026lab2/student-tests/track1_load.go
T
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

644 lines
20 KiB
Go

// Standalone black-box lab-1 generator. No application packages are imported.
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json/v2"
"errors"
"flag"
"fmt"
"io"
"math"
"mime"
"net/http"
"net/url"
"os"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
type message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type page struct {
Items []message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type requestError struct {
Kind string
Status int
}
func (e *requestError) Error() string { return fmt.Sprintf("%s (HTTP %d)", e.Kind, e.Status) }
type api struct {
base string
client *http.Client
}
// Entire response is consumed; transport reuses connections. No retries or redirects.
func (a *api) call(method, path, actor string, body any, want int, out any) error {
var input io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return err
}
input = bytes.NewReader(b)
}
req, err := http.NewRequest(method, a.base+path, input)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
if actor != "" {
req.Header.Set("X-User-Id", actor)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := a.client.Do(req)
if err != nil {
return &requestError{Kind: "transport_or_timeout"}
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1))
if err != nil {
return &requestError{Kind: "transport_or_timeout"}
}
if len(b) > 2*1024*1024 {
return &requestError{Kind: "protocol", Status: resp.StatusCode}
}
media, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if resp.Header.Get("X-Request-Id") == "" || err != nil || media != "application/json" {
return &requestError{Kind: "protocol", Status: resp.StatusCode}
}
if resp.StatusCode >= 400 {
var e struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if json.Unmarshal(b, &e) != nil || e.Error.Code == "" || e.Error.Message == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") {
return &requestError{Kind: "protocol", Status: resp.StatusCode}
}
}
if resp.StatusCode != want {
return &requestError{Kind: "http_status", Status: resp.StatusCode}
}
if out != nil {
if json.Unmarshal(b, out, json.RejectUnknownMembers(true)) != nil {
return &requestError{Kind: "protocol", Status: resp.StatusCode}
}
}
return nil
}
func stamp(m message) (time.Time, error) {
if !strings.HasSuffix(m.CreatedAt, "Z") {
return time.Time{}, fmt.Errorf("non-UTC timestamp")
}
return time.Parse(time.RFC3339Nano, m.CreatedAt)
}
func less(a, b message) bool {
x, _ := stamp(a)
y, _ := stamp(b)
return x.Before(y) || (x.Equal(y) && a.ID < b.ID)
}
func valid(m message, chat string) error {
_, err := stamp(m)
if err != nil || len(m.ID) != 36 || m.ChatID != chat || len(m.SenderID) != 36 || m.Text == "" {
return fmt.Errorf("invalid Message")
}
return nil
}
func newUser(a *api, label string) (string, error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return "", err
}
var user struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
err := a.call("POST", "/api/v1/users", "", map[string]any{"username": "t1_" + label + "_" + hex.EncodeToString(b), "display_name": "Synthetic track 1"}, 201, &user)
if err == nil && len(user.ID) != 36 {
err = fmt.Errorf("invalid User ID")
}
return user.ID, err
}
func newChat(a *api, users []string) (string, error) {
var chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
err := a.call("POST", "/api/v1/chats", users[0], map[string]any{"title": "Synthetic track 1", "member_ids": users}, 201, &chat)
if err == nil && len(chat.ID) != 36 {
err = fmt.Errorf("invalid Chat ID")
}
return chat.ID, err
}
func post(a *api, actor, chat, text string) (message, error) {
var m message
err := a.call("POST", "/api/v1/chats/"+chat+"/messages", actor, map[string]string{"text": text}, 201, &m)
if err == nil {
err = valid(m, chat)
}
if err == nil && (m.Text != text || m.SenderID != actor) {
err = fmt.Errorf("POST changed text or sender")
}
return m, err
}
func read(a *api, actor, path string, limit int) (page, error) {
var p page
err := a.call("GET", path, actor, nil, 200, &p)
if err != nil {
return p, err
}
if p.Items == nil || len(p.Items) > limit || (p.NextCursor != nil && (*p.NextCursor == "" || len(p.Items) != limit)) {
return p, fmt.Errorf("invalid page or cursor")
}
return p, nil
}
func pathFor(chat string, limit int, cursor string) string {
p := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit)
if cursor != "" {
p += "&cursor=" + url.QueryEscape(cursor)
}
return p
}
// Uses the opaque server cursor, exact nanosecond timestamps and full Message equality.
func walk(a *api, actor, chat string, limit, bound int) ([]message, map[int]string, error) {
all := make([]message, 0)
seen := map[string]bool{}
cursors := map[int]string{0: ""}
cursor := ""
for {
p, err := read(a, actor, pathFor(chat, limit, cursor), limit)
if err != nil {
return nil, nil, err
}
for _, m := range p.Items {
if err := valid(m, chat); err != nil {
return nil, nil, err
}
if seen[m.ID] || (len(all) > 0 && !less(all[len(all)-1], m)) {
return nil, nil, fmt.Errorf("duplicate or unordered history")
}
seen[m.ID] = true
all = append(all, m)
if len(all) > bound {
return nil, nil, fmt.Errorf("history exceeded safety bound")
}
}
if p.NextCursor == nil {
break
}
if *p.NextCursor == cursor {
return nil, nil, fmt.Errorf("cursor did not advance")
}
cursor = *p.NextCursor
cursors[len(all)] = cursor
}
return all, cursors, nil
}
func sameHistory(all []message, expected map[string]message, allowExtras bool) (int, error) {
for _, m := range all {
old, ok := expected[m.ID]
if ok && old != m {
return 0, fmt.Errorf("acknowledged Message changed")
}
if !ok && !allowExtras {
return 0, fmt.Errorf("unexpected Message")
}
}
if len(all) < len(expected) {
return 0, fmt.Errorf("acknowledged messages missing")
}
seen := map[string]bool{}
for _, m := range all {
seen[m.ID] = true
}
for id := range expected {
if !seen[id] {
return 0, fmt.Errorf("acknowledged messages missing")
}
}
return len(all) - len(expected), nil
}
func payload(index int64, size int) string {
prefix := fmt.Sprintf("synthetic-%012d-", index)
return prefix + strings.Repeat("x", size-len(prefix))
}
func seed(a *api, users []string, chat string, count, size int) (map[string]message, error) {
var next atomic.Int64
var mu sync.Mutex
expected := map[string]message{}
errs := make(chan error, len(users))
var wg sync.WaitGroup
for _, actor := range users {
wg.Add(1)
go func(actor string) {
defer wg.Done()
for {
i := int(next.Add(1)) - 1
if i >= count {
return
}
m, err := post(a, actor, chat, payload(int64(i), size))
if err != nil {
errs <- err
return
}
mu.Lock()
if _, exists := expected[m.ID]; exists {
mu.Unlock()
errs <- fmt.Errorf("duplicate POST ID")
return
}
expected[m.ID] = m
mu.Unlock()
}
}(actor)
}
wg.Wait()
close(errs)
for err := range errs {
return nil, err
}
return expected, nil
}
func event(name string, data any) {
if json.MarshalWrite(os.Stdout, map[string]any{"event": name, "data": data}) == nil {
fmt.Fprintln(os.Stdout)
}
}
func cpuSeconds() float64 {
var usage syscall.Rusage
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) != nil {
return -1
}
return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1e6
}
type operationStats struct {
Successes int `json:"successful_requests"`
Errors map[string]int `json:"errors"`
Latencies []float64 `json:"-"`
}
type stats struct {
Read operationStats
Write operationStats
}
func newStats() stats {
return stats{Read: operationStats{Errors: map[string]int{}}, Write: operationStats{Errors: map[string]int{}}}
}
func summary(s operationStats, elapsed float64) map[string]any {
sort.Float64s(s.Latencies)
var p50, p95, p99 any
percentile := func(p float64) float64 { return s.Latencies[int(math.Ceil(p*float64(len(s.Latencies))))-1] }
if len(s.Latencies) > 0 {
p50 = percentile(.5)
p95 = percentile(.95)
p99 = percentile(.99)
}
errors := 0
for _, n := range s.Errors {
errors += n
}
ratio := 0.0
if errors+s.Successes > 0 {
ratio = float64(errors) / float64(errors+s.Successes)
}
return map[string]any{"successful_requests": s.Successes, "failed_requests": errors, "error_ratio": ratio, "errors": s.Errors, "successful_rps": float64(s.Successes) / elapsed, "successful_latency_ms": map[string]any{"p50": p50, "p95": p95, "p99": p99}}
}
func classify(err error) string {
var e *requestError
if errors.As(err, &e) {
return fmt.Sprintf("%s:%d", e.Kind, e.Status)
}
return "protocol_or_integrity"
}
// Closed loop: one outstanding request per goroutine. Request deadlines include body reads.
func phase(a *api, users []string, chat string, paths []string, pages [][]message, concurrency, limit, size int, duration time.Duration, mixed bool, expected map[string]message, next *atomic.Int64) map[string]any {
start := make(chan struct{})
ready := sync.WaitGroup{}
done := sync.WaitGroup{}
ready.Add(concurrency)
done.Add(concurrency)
results := make([]stats, concurrency)
var mu sync.Mutex
var deadline time.Time
for worker := 0; worker < concurrency; worker++ {
go func(worker int) {
defer done.Done()
s := newStats()
ready.Done()
<-start
iteration := 0
for time.Now().Before(deadline) {
write := mixed && (iteration+worker)%20 == 0
bucket := &s.Read
if write {
bucket = &s.Write
}
began := time.Now()
var err error
if write {
m, e := post(a, users[worker%len(users)], chat, payload(next.Add(1), size))
err = e
if err == nil {
mu.Lock()
if _, exists := expected[m.ID]; exists {
err = fmt.Errorf("duplicate POST ID")
} else {
expected[m.ID] = m
}
mu.Unlock()
}
}
if !write {
idx := (iteration + worker) % len(paths)
var p page
p, err = read(a, users[worker%len(users)], paths[idx], limit)
if err == nil {
if len(p.Items) != len(pages[idx]) {
err = fmt.Errorf("fixed page changed")
} else {
for i, m := range p.Items {
if m != pages[idx][i] {
err = fmt.Errorf("fixed page changed")
break
}
}
}
}
}
elapsed := float64(time.Since(began).Nanoseconds()) / 1e6
if err == nil {
bucket.Successes++
bucket.Latencies = append(bucket.Latencies, elapsed)
} else {
bucket.Errors[classify(err)]++
}
iteration++
}
results[worker] = s
}(worker)
}
ready.Wait()
began := time.Now()
cpu := cpuSeconds()
deadline = began.Add(duration)
close(start)
done.Wait()
elapsed := time.Since(began).Seconds()
cpu = cpuSeconds() - cpu
combined := newStats()
for _, s := range results {
for _, pair := range [][2]*operationStats{{&combined.Read, &s.Read}, {&combined.Write, &s.Write}} {
pair[0].Successes += pair[1].Successes
pair[0].Latencies = append(pair[0].Latencies, pair[1].Latencies...)
for k, n := range pair[1].Errors {
pair[0].Errors[k] += n
}
}
}
return map[string]any{"requested_seconds": duration.Seconds(), "elapsed_seconds": elapsed, "client_cpu_seconds": cpu, "client_cpu_cores": cpu / elapsed, "read": summary(combined.Read, elapsed), "write": summary(combined.Write, elapsed)}
}
func correctness(a *api, users []string, chat string, expected map[string]message, size int) (map[string]any, error) {
// Limits vary and the final page is partial; all seed acknowledgements must survive.
var initial []message
for _, limit := range []int{1, 7, 50, 100} {
all, _, err := walk(a, users[0], chat, limit, len(expected))
if err != nil {
return nil, err
}
if _, err = sameHistory(all, expected, false); err != nil {
return nil, err
}
initial = all
}
first, err := read(a, users[0], pathFor(chat, 3, ""), 3)
if err != nil {
return nil, err
}
if first.NextCursor == nil {
return nil, fmt.Errorf("missing cursor")
}
second, err := read(a, users[0], pathFor(chat, 79, *first.NextCursor), 79)
if err != nil {
return nil, err
}
for i, m := range append(first.Items, second.Items...) {
if m != initial[i] {
return nil, fmt.Errorf("changing limit lost or reordered messages")
}
}
other, err := newChat(a, users)
if err != nil {
return nil, err
}
if err = a.call("GET", pathFor(other, 50, *first.NextCursor), users[0], nil, 400, nil); err != nil {
return nil, err
}
outsider, err := newUser(a, "outsider")
if err != nil {
return nil, err
}
if err = a.call("GET", pathFor(chat, 50, ""), outsider, nil, 404, nil); err != nil {
return nil, err
}
empty, err := read(a, users[0], pathFor(other, 50, ""), 50)
if err != nil {
return nil, err
}
if len(empty.Items) != 0 || empty.NextCursor != nil {
return nil, fmt.Errorf("invalid empty history")
}
start := make(chan struct{})
var wg sync.WaitGroup
errs := make(chan error, 13)
var mu sync.Mutex
seedCount := len(expected)
for w, actor := range users {
wg.Add(1)
go func(w int, actor string) {
defer wg.Done()
<-start
for i := 0; i < 10; i++ {
m, e := post(a, actor, chat, payload(int64(seedCount+w*10+i), size))
if e != nil {
errs <- e
return
}
mu.Lock()
if _, exists := expected[m.ID]; exists {
mu.Unlock()
errs <- fmt.Errorf("duplicate POST ID")
return
}
expected[m.ID] = m
mu.Unlock()
}
}(w, actor)
}
for _, limit := range []int{2, 17, 53} {
wg.Add(1)
go func(limit int) {
defer wg.Done()
<-start
all, _, e := walk(a, users[0], chat, limit, seedCount+100)
if e == nil {
_, e = sameHistory(all, mapFrom(initial), true)
}
if e != nil {
errs <- e
}
}(limit)
}
close(start)
wg.Wait()
close(errs)
for e := range errs {
return nil, e
}
all, _, err := walk(a, users[0], chat, 37, len(expected))
if err != nil {
return nil, err
}
if _, err = sameHistory(all, expected, false); err != nil {
return nil, err
}
return map[string]any{"status": "PASS", "seed_messages": seedCount, "concurrent_writes": 100, "writers": 10, "concurrent_history_walkers": 3, "final_unique_messages": len(all), "limits_checked": []int{1, 7, 50, 100}, "changed_limit": true, "foreign_chat": true, "cursor_binding": true, "empty_history": true, "ordering": "created_at nanoseconds, then id; full Message equality"}, nil
}
func mapFrom(all []message) map[string]message {
m := map[string]message{}
for _, item := range all {
m[item.ID] = item
}
return m
}
func execute() error {
base := flag.String("base-url", "http://127.0.0.1:8080", "isolated lab1 API")
mode := flag.String("mode", "load", "load or check")
history := flag.Int("history", 1000, "initial message count")
concurrency := flag.Int("concurrency", 5, "concurrent clients")
limit := flag.Int("page-size", 50, "history page size")
seconds := flag.Float64("duration", 30, "measurement seconds")
warmup := flag.Float64("warmup", 5, "warmup seconds")
timeout := flag.Float64("timeout", 5, "HTTP timeout seconds")
size := flag.Int("payload-bytes", 128, "ASCII text bytes")
workload := flag.String("workload", "read", "read or mixed (every 20th request writes)")
flag.Parse()
if (*mode != "load" && *mode != "check") || (*workload != "read" && *workload != "mixed") || *limit < 1 || *limit > 100 || *history < 2**limit || *concurrency < 1 || *concurrency > 256 || *seconds < 1 || *warmup < 0 || *timeout <= 0 || *size < 32 || *size > 4000 {
return fmt.Errorf("invalid arguments")
}
transport := &http.Transport{MaxIdleConns: 512, MaxIdleConnsPerHost: 512, MaxConnsPerHost: 512, IdleConnTimeout: 90 * time.Second, DisableCompression: true}
defer transport.CloseIdleConnections()
a := &api{base: strings.TrimRight(*base, "/"), client: &http.Client{Transport: transport, Timeout: time.Duration(*timeout * float64(time.Second)), CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
if err := a.call("GET", "/health/ready", "", nil, 200, nil); err != nil {
return err
}
users := make([]string, 10)
for i := range users {
u, err := newUser(a, fmt.Sprint(i))
if err != nil {
return err
}
users[i] = u
}
chat, err := newChat(a, users)
if err != nil {
return err
}
event("seed_start", map[string]any{"messages": *history})
expected, err := seed(a, users, chat, *history, *size)
if err != nil {
return err
}
if *mode == "check" {
result, err := correctness(a, users, chat, expected, *size)
if err != nil {
return err
}
event("result", result)
return nil
}
all, cursors, err := walk(a, users[0], chat, *limit, *history)
if err != nil {
return err
}
if _, err = sameHistory(all, expected, false); err != nil {
return err
}
positions := []int{0, (*history / 2 / *limit) * *limit, ((*history - *limit) / *limit) * *limit}
paths := make([]string, 3)
pages := make([][]message, 3)
for i, pos := range positions {
paths[i] = pathFor(chat, *limit, cursors[pos])
pages[i] = append([]message(nil), all[pos:pos+*limit]...)
}
event("fixture_ready", map[string]any{"messages": len(all), "page_positions": positions})
var next atomic.Int64
next.Store(int64(*history))
mixed := *workload == "mixed"
event("warmup_start", nil)
if *warmup > 0 {
phase(a, users, chat, paths, pages, *concurrency, *limit, *size, time.Duration(*warmup*float64(time.Second)), mixed, expected, &next)
}
measurementInitial := len(expected)
event("measurement_start", map[string]any{"history_messages": measurementInitial})
metrics := phase(a, users, chat, paths, pages, *concurrency, *limit, *size, time.Duration(*seconds*float64(time.Second)), mixed, expected, &next)
event("measurement_complete", nil)
all, _, err = walk(a, users[0], chat, 100, int(next.Load())+*concurrency+*history)
if err != nil {
return err
}
extra, err := sameHistory(all, expected, mixed)
if err != nil {
return err
}
protocolFailures := 0
for _, op := range []string{"read", "write"} {
for key, n := range metrics[op].(map[string]any)["errors"].(map[string]int) {
if strings.HasPrefix(key, "protocol") {
protocolFailures += n
}
}
}
if protocolFailures > 0 {
return fmt.Errorf("load observed %d protocol/integrity failures", protocolFailures)
}
event("result", map[string]any{"status": "PASS", "generator": "Go " + runtime.Version() + "; HTTP/1.1 keep-alive, closed loop, no retries", "generator_logical_cpus": runtime.NumCPU(), "workload": *workload, "initial_messages": *history, "measurement_initial_messages": measurementInitial, "final_messages": len(all), "concurrency": *concurrency, "page_size": *limit, "page_positions": positions, "payload_bytes": *size, "metrics": metrics, "integrity": map[string]any{"acknowledged_messages": len(expected), "missing_acknowledged_messages": 0, "unacknowledged_messages": extra, "unique_messages": len(all), "full_message_equality": true}, "limitations": []string{"Success latency only; errors separate. Closed loop has coordinated omission.", "Client includes JSON decoding, equality checks and OS scheduling; this is not a proof of maximum capacity.", "RSS/CPU are collected externally. Mixed workload grows history during warmup and measurement.", "Fixed read pages assume no backwards wall-clock jump during the experiment. No snapshots are required of the API."}})
return nil
}
func main() {
if err := execute(); err != nil {
event("failure", map[string]string{"reason": err.Error()})
os.Exit(1)
}
}