test: add resilience and benchmark verification

This commit is contained in:
2026-09-24 10:50:50 +03:00
parent 872b69f90e
commit 1f511728c9
13 changed files with 1203 additions and 0 deletions
+165
View File
@@ -0,0 +1,165 @@
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/google/uuid"
)
type apiClient struct {
baseURL string
client *http.Client
token string
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("PASS: PostgreSQL and Valkey outage recovery")
}
func run() error {
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL")
flag.Parse()
client := &apiClient{baseURL: *baseURL, client: &http.Client{Timeout: 10 * time.Second}}
if err := client.registerAndLogin(); err != nil {
return err
}
if err := client.expect(http.MethodGet, "/api/v1/users/me", http.StatusOK, true); err != nil {
return err
}
if err := verifyOutage(client, "valkey"); err != nil {
return err
}
return verifyOutage(client, "postgres")
}
func (c *apiClient) registerAndLogin() error {
username := "dep_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
password := "T3st-" + uuid.NewString()
body := map[string]string{"username": username, "display_name": "Dependency check", "password": password}
payload, err := json.Marshal(body)
if err != nil {
return err
}
request, err := http.NewRequest(http.MethodPost, c.baseURL+"/api/v1/users", bytes.NewReader(payload))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
response, err := c.client.Do(request)
if err != nil {
return fmt.Errorf("register: %w", err)
}
if err := closeResponse(response, http.StatusCreated); err != nil {
return fmt.Errorf("register: %w", err)
}
request, err = http.NewRequest(http.MethodPost, c.baseURL+"/api/v1/auth/sessions", nil)
if err != nil {
return err
}
request.SetBasicAuth(username, password)
response, err = c.client.Do(request)
if err != nil {
return fmt.Errorf("login: %w", err)
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusCreated {
return fmt.Errorf("login status = %d", response.StatusCode)
}
var session struct {
Token string `json:"token"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&session); err != nil {
return fmt.Errorf("decode session: %w", err)
}
if session.Token == "" {
return fmt.Errorf("login returned an empty token")
}
c.token = session.Token
return nil
}
func verifyOutage(client *apiClient, service string) (returnErr error) {
if err := compose("stop", service); err != nil {
return err
}
defer func() {
if err := compose("up", "-d", "--wait", "--wait-timeout", "90", service); returnErr == nil && err != nil {
returnErr = err
}
}()
if err := client.expectEventually("/health/ready", http.StatusServiceUnavailable, false); err != nil {
return fmt.Errorf("%s readiness outage: %w", service, err)
}
if err := client.expectEventually("/api/v1/users/me", http.StatusServiceUnavailable, true); err != nil {
return fmt.Errorf("%s business outage: %w", service, err)
}
if err := compose("up", "-d", "--wait", "--wait-timeout", "90", service); err != nil {
return err
}
if err := client.expectEventually("/health/ready", http.StatusOK, false); err != nil {
return fmt.Errorf("%s readiness recovery: %w", service, err)
}
if err := client.expectEventually("/api/v1/users/me", http.StatusOK, true); err != nil {
return fmt.Errorf("%s session recovery: %w", service, err)
}
return nil
}
func compose(arguments ...string) error {
command := exec.Command("docker", append([]string{"compose"}, arguments...)...)
if output, err := command.CombinedOutput(); err != nil {
return fmt.Errorf("docker compose %v: %w: %s", arguments, err, bytes.TrimSpace(output))
}
return nil
}
func (c *apiClient) expectEventually(path string, status int, authenticated bool) error {
deadline := time.Now().Add(20 * time.Second)
var lastErr error
for time.Now().Before(deadline) {
lastErr = c.expect(http.MethodGet, path, status, authenticated)
if lastErr == nil {
return nil
}
time.Sleep(200 * time.Millisecond)
}
return lastErr
}
func (c *apiClient) expect(method, path string, status int, authenticated bool) error {
request, err := http.NewRequest(method, c.baseURL+path, nil)
if err != nil {
return err
}
if authenticated {
request.Header.Set("Authorization", "Bearer "+c.token)
}
response, err := c.client.Do(request)
if err != nil {
return err
}
return closeResponse(response, status)
}
func closeResponse(response *http.Response, status int) error {
defer func() { _ = response.Body.Close() }()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 1<<20))
if response.StatusCode != status {
return fmt.Errorf("status = %d, want %d", response.StatusCode, status)
}
return nil
}
+236
View File
@@ -0,0 +1,236 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const experimentSchema = "lab2_experiment"
type report struct {
GeneratedAt string `json:"generated_at"`
GoVersion string `json:"go_version"`
Platform string `json:"platform"`
CPUs int `json:"cpus"`
Messages int `json:"messages"`
Distribution []int `json:"chat_distribution"`
SeedDuration float64 `json:"seed_duration_seconds"`
Plans []planResult `json:"plans"`
Writes []writeResult `json:"writes"`
}
type planResult struct {
Name string `json:"name"`
DDL string `json:"ddl"`
Plan json.RawMessage `json:"plan"`
}
type writeResult struct {
Name string `json:"name"`
Rows int `json:"rows"`
SamplesSeconds []float64 `json:"samples_seconds"`
MedianSeconds float64 `json:"median_seconds"`
RowsPerSec float64 `json:"rows_per_second"`
IndexBytes int64 `json:"index_bytes"`
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
urlFile := flag.String("database-url-file", "secrets/database_url", "file containing the PostgreSQL URL")
output := flag.String("output", "evidence/lab2-track2.json", "result JSON path")
messages := flag.Int("messages", 100000, "number of messages")
writeRows := flag.Int("write-rows", 10000, "rows per write test")
flag.Parse()
if *messages < 100000 {
return fmt.Errorf("messages must be at least 100000")
}
if *writeRows < 1000 {
return fmt.Errorf("write-rows must be at least 1000")
}
data, err := os.ReadFile(*urlFile)
if err != nil {
return fmt.Errorf("read database URL: %w", err)
}
pool, err := pgxpool.New(context.Background(), strings.TrimSpace(string(data)))
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer pool.Close()
distribution := messageDistribution(*messages, 20)
seedStarted := time.Now()
chatIDs, err := seed(context.Background(), pool, distribution)
if err != nil {
return err
}
result := report{
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
GoVersion: runtime.Version(), Platform: runtime.GOOS + "/" + runtime.GOARCH,
CPUs: runtime.NumCPU(), Messages: *messages, Distribution: distribution,
SeedDuration: time.Since(seedStarted).Seconds(),
}
result.Plans, err = comparePlans(context.Background(), pool, chatIDs[len(chatIDs)-1], distribution[len(distribution)-1])
if err != nil {
return err
}
result.Writes, err = compareWrites(context.Background(), pool, *writeRows)
if err != nil {
return err
}
payload, err := json.MarshalIndent(result, "", " ")
if err != nil {
return fmt.Errorf("encode report: %w", err)
}
if err := os.WriteFile(*output, append(payload, '\n'), 0o644); err != nil {
return fmt.Errorf("write report: %w", err)
}
return nil
}
func messageDistribution(total, chats int) []int {
distribution := make([]int, chats)
distribution[0] = total * 60 / 100
distribution[1] = total * 20 / 100
distribution[2] = total * 10 / 100
remaining := total - distribution[0] - distribution[1] - distribution[2]
for i := 3; i < chats; i++ {
distribution[i] = remaining / (chats - 3)
}
for assigned := sum(distribution); assigned < total; assigned++ {
distribution[chats-1]++
}
return distribution
}
func sum(values []int) int {
var result int
for _, value := range values {
result += value
}
return result
}
func seed(ctx context.Context, pool *pgxpool.Pool, distribution []int) ([]uuid.UUID, error) {
if _, err := pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+experimentSchema+` CASCADE; CREATE SCHEMA `+experimentSchema+`; CREATE TABLE `+experimentSchema+`.messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, text text NOT NULL)`); err != nil {
return nil, fmt.Errorf("create experiment table: %w", err)
}
chatIDs := make([]uuid.UUID, len(distribution))
for i := range chatIDs {
chatIDs[i] = uuid.NewSHA1(uuid.NameSpaceOID, []byte("chat-"+strconv.Itoa(i)))
}
base := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
rows := make([][]any, 0, sum(distribution))
sequence := 0
for chatIndex, count := range distribution {
for i := range count {
id := uuid.NewSHA1(chatIDs[chatIndex], []byte(strconv.Itoa(i)))
text := strings.Repeat("m", 32+(i%16)*32)
sequence = i*len(distribution) + chatIndex
rows = append(rows, []any{id, chatIDs[chatIndex], base.Add(time.Duration(sequence) * time.Microsecond), text})
}
}
if _, err := pool.CopyFrom(ctx, pgx.Identifier{experimentSchema, "messages"}, []string{"id", "chat_id", "created_at", "text"}, pgx.CopyFromRows(rows)); err != nil {
return nil, fmt.Errorf("seed messages: %w", err)
}
return chatIDs, nil
}
func comparePlans(ctx context.Context, pool *pgxpool.Pool, chatID uuid.UUID, count int) ([]planResult, error) {
base := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
middle := count / 2
cursorTime := base.Add(time.Duration(middle*20+19) * time.Microsecond)
cursorID := uuid.NewSHA1(chatID, []byte(strconv.Itoa(middle)))
candidates := []struct {
name string
ddl string
}{
{"history_composite", `CREATE INDEX experiment_history_idx ON ` + experimentSchema + `.messages (chat_id, created_at, id)`},
{"global_time", `CREATE INDEX experiment_history_idx ON ` + experimentSchema + `.messages (created_at, id)`},
}
results := make([]planResult, 0, len(candidates))
for _, candidate := range candidates {
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS `+experimentSchema+`.experiment_history_idx; `+candidate.ddl+`; ANALYZE `+experimentSchema+`.messages`); err != nil {
return nil, fmt.Errorf("prepare %s index: %w", candidate.name, err)
}
const explain = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT id, chat_id, created_at, text
FROM lab2_experiment.messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT 100`
var raw []byte
if err := pool.QueryRow(ctx, explain, chatID, cursorTime, cursorID).Scan(&raw); err != nil {
return nil, fmt.Errorf("explain %s: %w", candidate.name, err)
}
results = append(results, planResult{Name: candidate.name, DDL: candidate.ddl, Plan: json.RawMessage(raw)})
}
return results, nil
}
func compareWrites(ctx context.Context, pool *pgxpool.Pool, rows int) ([]writeResult, error) {
const repetitions = 5
candidates := []struct {
name string
ddl string
}{
{"no_secondary_index", ""},
{"history_composite", `CREATE INDEX write_history_idx ON ` + experimentSchema + `.write_messages (chat_id, created_at, id)`},
{"global_time", `CREATE INDEX write_history_idx ON ` + experimentSchema + `.write_messages (created_at, id)`},
}
results := make([]writeResult, 0, len(candidates))
for _, candidate := range candidates {
samples := make([]float64, 0, repetitions)
var indexBytes int64
for repetition := range repetitions {
if _, err := pool.Exec(ctx, `DROP TABLE IF EXISTS `+experimentSchema+`.write_messages; CREATE TABLE `+experimentSchema+`.write_messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, text text NOT NULL); `+candidate.ddl); err != nil {
return nil, fmt.Errorf("prepare write test %s: %w", candidate.name, err)
}
values := make([][]any, rows)
base := time.Date(2026, time.January, 1, 0, 0, repetition, 0, time.UTC)
for i := range rows {
values[i] = []any{
uuid.NewSHA1(uuid.NameSpaceOID, []byte(strconv.Itoa(i))),
uuid.NewSHA1(uuid.NameSpaceURL, []byte(strconv.Itoa(i%20))),
base.Add(time.Duration(i) * time.Microsecond),
"message",
}
}
started := time.Now()
if _, err := pool.CopyFrom(ctx, pgx.Identifier{experimentSchema, "write_messages"}, []string{"id", "chat_id", "created_at", "text"}, pgx.CopyFromRows(values)); err != nil {
return nil, fmt.Errorf("write test %s: %w", candidate.name, err)
}
samples = append(samples, time.Since(started).Seconds())
if candidate.ddl != "" {
if err := pool.QueryRow(ctx, `SELECT pg_relation_size($1::regclass)`, experimentSchema+".write_history_idx").Scan(&indexBytes); err != nil {
return nil, fmt.Errorf("read %s index size: %w", candidate.name, err)
}
}
}
sort.Float64s(samples)
median := samples[len(samples)/2]
results = append(results, writeResult{
Name: candidate.name, Rows: rows, SamplesSeconds: samples,
MedianSeconds: median, RowsPerSec: float64(rows) / median, IndexBytes: indexBytes,
})
}
return results, nil
}
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"strings"
"testing"
)
func TestRunRequiresAddress(t *testing.T) {
tests := []struct {
name string
host string
port string
want string
}{
{name: "missing host", port: "8080", want: "APP_HOST is required"},
{name: "missing port", host: "127.0.0.1", want: "APP_PORT is required"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("APP_HOST", tt.host)
t.Setenv("APP_PORT", tt.port)
if err := run(nil); err == nil || !strings.Contains(err.Error(), tt.want) {
t.Fatalf("run() error = %v, want %q", err, tt.want)
}
})
}
}