forked from mtusi2026/mtusi2026lab2
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
207 lines
6.6 KiB
Go
207 lines
6.6 KiB
Go
// Standalone experiment; production constructors and timeouts are never used.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
|
|
func save(path string, v any) error {
|
|
b, e := json.MarshalIndent(v, "", " ")
|
|
if e != nil {
|
|
return e
|
|
}
|
|
return os.WriteFile(path, append(b, '\n'), 0600)
|
|
}
|
|
func snapshot(c *redis.Client, out, phase string) (map[string]any, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
|
defer cancel()
|
|
settings := map[string]string{}
|
|
for _, pattern := range []string{"append*", "*aof*", "no-appendfsync-on-rewrite"} {
|
|
values, e := c.ConfigGet(ctx, pattern).Result()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
for k, v := range values {
|
|
settings[k] = v
|
|
}
|
|
}
|
|
info, e := c.Info(ctx, "persistence").Result()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
server, e := c.Info(ctx, "server").Result()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
if e = os.WriteFile(filepath.Join(out, "persistence-"+phase+".info"), []byte(info), 0600); e != nil {
|
|
return nil, e
|
|
}
|
|
if e = os.WriteFile(filepath.Join(out, "server-"+phase+".info"), []byte(server), 0600); e != nil {
|
|
return nil, e
|
|
}
|
|
s := map[string]any{"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "aof_settings": settings, "info_persistence": info, "info_server": server}
|
|
return s, save(filepath.Join(out, "snapshot-"+phase+".json"), s)
|
|
}
|
|
|
|
func measure(c *redis.Client, number, round, budget, pause int) map[string]any {
|
|
key := "waitaof-probe:" + uuid.NewString()
|
|
errors := map[string]string{}
|
|
s := map[string]any{"number": number, "round": round, "waitaof_timeout_ms": budget, "scheduled_pause_ms": pause, "synthetic_key": key, "errors": errors, "local_fsynced": nil, "replicas_fsynced": nil}
|
|
// Conn pins all commands to one physical connection. IDs before/after also
|
|
// detect reconnects; such samples are invalid rather than acknowledged.
|
|
conn := c.Conn()
|
|
defer conn.Close()
|
|
initCtx, initCancel := context.WithTimeout(context.Background(), 12*time.Second)
|
|
before, e := conn.ClientID(initCtx).Result()
|
|
initCancel()
|
|
if e != nil {
|
|
errors["client_id_before"] = e.Error()
|
|
return s
|
|
}
|
|
s["client_id_before"] = before
|
|
paused := time.Now()
|
|
time.Sleep(time.Duration(pause) * time.Millisecond)
|
|
s["actual_pause_ms"] = ms(time.Since(paused))
|
|
// The pause does not consume any of the command deadline.
|
|
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
|
defer cancel()
|
|
start := time.Now()
|
|
s["write_started_at_utc"] = start.UTC().Format(time.RFC3339Nano)
|
|
e = conn.Set(ctx, key, "synthetic-waitaof-value", time.Minute).Err()
|
|
s["set_ms"] = ms(time.Since(start))
|
|
if e != nil {
|
|
errors["set"] = e.Error()
|
|
} else {
|
|
t := time.Now()
|
|
deleted, delErr := conn.Del(ctx, key).Result()
|
|
s["del_ms"] = ms(time.Since(t))
|
|
s["deleted"] = deleted
|
|
if delErr != nil {
|
|
errors["del"] = delErr.Error()
|
|
} else {
|
|
if deleted != 1 {
|
|
errors["deleted_count"] = "expected exactly one newly written key"
|
|
}
|
|
t = time.Now()
|
|
reply, waitErr := conn.Do(ctx, "WAITAOF", 1, 0, budget).Slice()
|
|
s["waitaof_ms"] = ms(time.Since(t))
|
|
if waitErr != nil {
|
|
errors["waitaof"] = waitErr.Error()
|
|
} else if len(reply) != 2 {
|
|
errors["reply"] = "expected two counters"
|
|
} else {
|
|
local, okLocal := reply[0].(int64)
|
|
replicas, okReplicas := reply[1].(int64)
|
|
if !okLocal || !okReplicas {
|
|
errors["reply"] = "expected integer counters"
|
|
} else {
|
|
s["local_fsynced"] = local
|
|
s["replicas_fsynced"] = replicas
|
|
}
|
|
}
|
|
}
|
|
}
|
|
s["write_delete_wait_ms"] = ms(time.Since(start))
|
|
after, e := conn.ClientID(ctx).Result()
|
|
s["client_id_after"] = after
|
|
if e != nil {
|
|
errors["client_id_after"] = e.Error()
|
|
}
|
|
if before != after {
|
|
errors["pinned_connection"] = "connection ID changed"
|
|
}
|
|
exists, e := conn.Exists(ctx, key).Result()
|
|
s["exists_after"] = exists
|
|
if e != nil {
|
|
errors["exists"] = e.Error()
|
|
}
|
|
if exists != 0 {
|
|
errors["key_remains"] = "synthetic key was not deleted"
|
|
cleanup, done := context.WithTimeout(context.Background(), 8*time.Second)
|
|
defer done()
|
|
if e = conn.Del(cleanup, key).Err(); e != nil {
|
|
errors["cleanup"] = e.Error()
|
|
}
|
|
}
|
|
return s
|
|
}
|
|
|
|
func run(out string) error {
|
|
addr := os.Getenv("WAITAOF_TEST_REDIS_ADDR")
|
|
if addr == "" {
|
|
return fmt.Errorf("set WAITAOF_TEST_REDIS_ADDR for a dedicated test Redis")
|
|
}
|
|
c := redis.NewClient(&redis.Options{Addr: addr, DialTimeout: 8 * time.Second, ReadTimeout: 8 * time.Second, WriteTimeout: 8 * time.Second, PoolTimeout: 8 * time.Second, ContextTimeoutEnabled: true, MaxRetries: -1, PoolSize: 1})
|
|
defer c.Close()
|
|
before, e := snapshot(c, out, "before")
|
|
if e != nil {
|
|
return e
|
|
}
|
|
file, e := os.OpenFile(filepath.Join(out, "samples.jsonl"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer file.Close()
|
|
encoder := json.NewEncoder(file)
|
|
pauses := []int{0, 137, 359, 613, 887, 1109}
|
|
samples := []map[string]any{}
|
|
invalid := 0
|
|
for round := 1; round <= 3; round++ {
|
|
for i := range pauses {
|
|
pause := pauses[(i+round-1)%len(pauses)]
|
|
budgets := []int{1000, 3000}
|
|
if (round+i)%2 == 0 {
|
|
budgets = []int{3000, 1000}
|
|
}
|
|
for _, budget := range budgets {
|
|
s := measure(c, len(samples)+1, round, budget, pause)
|
|
samples = append(samples, s)
|
|
if len(s["errors"].(map[string]string)) > 0 {
|
|
invalid++
|
|
}
|
|
if e = encoder.Encode(s); e != nil {
|
|
return e
|
|
}
|
|
if e = file.Sync(); e != nil {
|
|
return e
|
|
}
|
|
fmt.Printf("sample=%d round=%d timeout_ms=%d pause_ms=%d wait_ms=%v local=%v replicas=%v errors=%d\n", len(samples), round, budget, pause, s["waitaof_ms"], s["local_fsynced"], s["replicas_fsynced"], len(s["errors"].(map[string]string)))
|
|
}
|
|
}
|
|
}
|
|
after, e := snapshot(c, out, "after")
|
|
if e != nil {
|
|
return e
|
|
}
|
|
result := map[string]any{"complete": true, "invalid_samples": invalid, "settings": map[string]any{"network_timeout_ms": 8000, "command_deadline_ms": 12000, "retries": 0, "pool_size": 1, "repetitions_per_pause_per_timeout": 3, "scheduled_pauses_ms": pauses, "ordering": "alternate timeout order and rotate pauses each round"}, "before": before, "after": after, "samples": samples}
|
|
if e = save(filepath.Join(out, "experiment.json"), result); e != nil {
|
|
return e
|
|
}
|
|
if invalid > 0 {
|
|
return fmt.Errorf("%d invalid samples; inspect errors in raw results", invalid)
|
|
}
|
|
return nil
|
|
}
|
|
func main() {
|
|
out := flag.String("output", "", "existing dedicated experiment directory")
|
|
flag.Parse()
|
|
if *out == "" {
|
|
fmt.Fprintln(os.Stderr, "-output is required")
|
|
os.Exit(2)
|
|
}
|
|
if e := run(*out); e != nil {
|
|
fmt.Fprintln(os.Stderr, e)
|
|
os.Exit(1)
|
|
}
|
|
}
|