edge-roll-blip: local restart witness (tcp, unix, hold-off control)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+310
−0
internal/edge/localhold_witness_test.go+310 −0
diff --git a/internal/edge/localhold_witness_test.go b/internal/edge/localhold_witness_test.go| new file mode 100644 |
| index 000000000..2e2480df7 |
| --- /dev/null |
| +++ b/internal/edge/localhold_witness_test.go |
| @@ -0,0 +1,310 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "runtime" |
| + "sort" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// witnessStats is what one restart run measured. p50, p99 and max are the |
| +// ADDED wait: each request's latency minus the baseline p50 (the latency of |
| +// requests that finished before the restart began). |
| +type witnessStats struct { |
| + requests, ok, s502, s503, other int |
| + p50, p99, max time.Duration |
| + // gap is how long the upstream refused, from the start of its Shutdown |
| + // until the new server was listening. |
| + gap time.Duration |
| +} |
| + |
| +const ( |
| + witnessHost = "shop.example.com" |
| + witnessWorkers = 8 |
| + // witnessPace is each worker's pause between requests. It keeps the load |
| + // steady rather than a spin; it is not a synchronization sleep. |
| + witnessPace = 5 * time.Millisecond |
| + witnessBaseline = time.Second |
| + witnessGap = 1500 * time.Millisecond |
| + witnessAfter = time.Second |
| +) |
| + |
| +type witnessSample struct { |
| + start, end time.Time |
| + status int // 0 = transport error |
| +} |
| + |
| +// witnessUpstream answers / and /healthz with 200. |
| +func witnessUpstream() *http.Server { |
| + mux := http.NewServeMux() |
| + ok := func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") } |
| + mux.HandleFunc("/", ok) |
| + mux.HandleFunc("/healthz", ok) |
| + return &http.Server{Handler: mux} |
| +} |
| + |
| +// runRestartWitness drives eight keep-alive workers through e (served by an |
| +// httptest server on 127.0.0.1) at the host witnessHost. listen binds the |
| +// upstream's fixed address and is called once per server: first to start it, |
| +// then again after the gap to bring the restarted one up. The runner does |
| +// baseline load, Shutdown with a 5 s drain, a gap in which the address |
| +// refuses, the restart, and load for another second. |
| +func runRestartWitness(t *testing.T, e *Edge, listen func() (net.Listener, error)) witnessStats { |
| + t.Helper() |
| + |
| + srv := httptest.NewServer(e) |
| + defer srv.Close() |
| + |
| + up1 := witnessUpstream() |
| + l1, err := listen() |
| + if err != nil { |
| + t.Fatalf("listen (first): %v", err) |
| + } |
| + go up1.Serve(l1) |
| + |
| + client := &http.Client{ |
| + Timeout: 15 * time.Second, |
| + Transport: &http.Transport{MaxIdleConnsPerHost: witnessWorkers}, |
| + } |
| + defer client.CloseIdleConnections() |
| + |
| + stop := make(chan struct{}) |
| + var ( |
| + mu sync.Mutex |
| + samples []witnessSample |
| + wg sync.WaitGroup |
| + ) |
| + for i := 0; i < witnessWorkers; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + var mine []witnessSample |
| + defer func() { |
| + mu.Lock() |
| + samples = append(samples, mine...) |
| + mu.Unlock() |
| + }() |
| + for { |
| + select { |
| + case <-stop: |
| + return |
| + default: |
| + } |
| + req, _ := http.NewRequest(http.MethodGet, srv.URL+"/", nil) |
| + req.Host = witnessHost |
| + s := witnessSample{start: time.Now()} |
| + resp, err := client.Do(req) |
| + if err == nil { |
| + _, err = io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + if err == nil { |
| + s.status = resp.StatusCode |
| + } |
| + } |
| + s.end = time.Now() |
| + mine = append(mine, s) |
| + select { |
| + case <-stop: |
| + return |
| + case <-time.After(witnessPace): |
| + } |
| + } |
| + }() |
| + } |
| + |
| + time.Sleep(witnessBaseline) |
| + |
| + // The restart, as the instance drain does it. |
| + shutStart := time.Now() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + if err := up1.Shutdown(ctx); err != nil { |
| + t.Errorf("upstream Shutdown: %v", err) |
| + } |
| + cancel() |
| + time.Sleep(witnessGap) |
| + |
| + up2 := witnessUpstream() |
| + l2, err := listen() |
| + if err != nil { |
| + close(stop) |
| + wg.Wait() |
| + t.Fatalf("listen (restart): %v", err) |
| + } |
| + restarted := time.Now() |
| + go up2.Serve(l2) |
| + defer up2.Close() |
| + |
| + time.Sleep(witnessAfter) |
| + close(stop) |
| + wg.Wait() |
| + |
| + // Baseline: requests that finished before the restart began. |
| + var base []time.Duration |
| + for _, s := range samples { |
| + if s.end.Before(shutStart) && s.status == http.StatusOK { |
| + base = append(base, s.end.Sub(s.start)) |
| + } |
| + } |
| + if len(base) == 0 { |
| + t.Fatalf("no baseline requests completed in %v", witnessBaseline) |
| + } |
| + sortDurations(base) |
| + baseP50 := percentile(base, 0.50) |
| + |
| + st := witnessStats{gap: restarted.Sub(shutStart)} |
| + var added []time.Duration |
| + for _, s := range samples { |
| + st.requests++ |
| + switch s.status { |
| + case http.StatusOK: |
| + st.ok++ |
| + case http.StatusBadGateway: |
| + st.s502++ |
| + case http.StatusServiceUnavailable: |
| + st.s503++ |
| + default: |
| + st.other++ |
| + } |
| + w := s.end.Sub(s.start) - baseP50 |
| + if w < 0 { |
| + w = 0 |
| + } |
| + added = append(added, w) |
| + } |
| + sortDurations(added) |
| + st.p50 = percentile(added, 0.50) |
| + st.p99 = percentile(added, 0.99) |
| + st.max = added[len(added)-1] |
| + return st |
| +} |
| + |
| +func sortDurations(d []time.Duration) { |
| + sort.Slice(d, func(i, j int) bool { return d[i] < d[j] }) |
| +} |
| + |
| +// percentile reads the q quantile from an ascending slice. |
| +func percentile(d []time.Duration, q float64) time.Duration { |
| + if len(d) == 0 { |
| + return 0 |
| + } |
| + return d[int(float64(len(d)-1)*q)] |
| +} |
| + |
| +func logWitness(t *testing.T, route string, st witnessStats) { |
| + t.Helper() |
| + t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v", |
| + route, st.gap.Round(time.Millisecond), st.requests, st.ok, st.s502, st.s503, st.other, st.p50, st.p99, st.max) |
| +} |
| + |
| +// reserveLoopbackAddr picks a free 127.0.0.1 port and releases it, so the |
| +// route can name an address the upstream binds later. |
| +func reserveLoopbackAddr(t *testing.T) string { |
| + t.Helper() |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatalf("reserve port: %v", err) |
| + } |
| + addr := l.Addr().String() |
| + l.Close() |
| + return addr |
| +} |
| + |
| +// listenTCPFixed binds addr, retrying briefly in case the kernel has not yet |
| +// released it. |
| +func listenTCPFixed(addr string) func() (net.Listener, error) { |
| + return func() (net.Listener, error) { |
| + var lastErr error |
| + for i := 0; i < 50; i++ { |
| + l, err := net.Listen("tcp", addr) |
| + if err == nil { |
| + return l, nil |
| + } |
| + lastErr = err |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + return nil, lastErr |
| + } |
| +} |
| + |
| +func witnessTCPEdge(t *testing.T, hold localHold) (*Edge, func() (net.Listener, error)) { |
| + t.Helper() |
| + addr := reserveLoopbackAddr(t) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addr: addr, Status: "ready"}); err != nil { |
| + t.Fatalf("upsert: %v", err) |
| + } |
| + e, err := newEdge(reg, nil, hold) |
| + if err != nil { |
| + t.Fatalf("newEdge: %v", err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + return e, listenTCPFixed(addr) |
| +} |
| + |
| +// TestLocalUpstreamRestartWitness restarts a local upstream under load and |
| +// counts what the edge did with the requests that arrived while it refused. |
| +// Its log lines are the evidence quoted for the roll blip. |
| +func TestLocalUpstreamRestartWitness(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("restart witness takes about 5 s") |
| + } |
| + |
| + t.Run("tcp", func(t *testing.T) { |
| + t.Parallel() |
| + e, listen := witnessTCPEdge(t, defaultLocalHold()) |
| + st := runRestartWitness(t, e, listen) |
| + logWitness(t, "tcp", st) |
| + if st.s502 != 0 || st.s503 != 0 || st.other != 0 { |
| + t.Errorf("failures during restart: 502=%d 503=%d other=%d, want none", st.s502, st.s503, st.other) |
| + } |
| + if st.max >= st.gap+time.Second { |
| + t.Errorf("max added wait %v, want under gap+1s = %v", st.max, st.gap+time.Second) |
| + } |
| + }) |
| + |
| + t.Run("unix", func(t *testing.T) { |
| + t.Parallel() |
| + if runtime.GOOS == "windows" { |
| + t.Skip("unix sockets") |
| + } |
| + sock := filepath.Join(shortSockDir(t), "app.sock") |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "instance", Socket: sock, Status: "ready"}); err != nil { |
| + t.Fatalf("upsert: %v", err) |
| + } |
| + e, err := newEdge(reg, nil, defaultLocalHold()) |
| + if err != nil { |
| + t.Fatalf("newEdge: %v", err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + st := runRestartWitness(t, e, func() (net.Listener, error) { return net.Listen("unix", sock) }) |
| + logWitness(t, "unix", st) |
| + if st.s502 != 0 || st.s503 != 0 || st.other != 0 { |
| + t.Errorf("failures during restart: 502=%d 503=%d other=%d, want none", st.s502, st.s503, st.other) |
| + } |
| + if st.max >= st.gap+time.Second { |
| + t.Errorf("max added wait %v, want under gap+1s = %v", st.max, st.gap+time.Second) |
| + } |
| + }) |
| + |
| + // Negative control: with the dial hold off the same restart must 502, |
| + // or the witness above could not have failed. |
| + t.Run("tcp-hold-off", func(t *testing.T) { |
| + t.Parallel() |
| + e, listen := witnessTCPEdge(t, noHold()) |
| + st := runRestartWitness(t, e, listen) |
| + logWitness(t, "tcp-hold-off", st) |
| + if st.s502 == 0 { |
| + t.Errorf("502 count = 0 with the hold off, want > 0 (the witness cannot fail)") |
| + } |
| + }) |
| +} |