Files
mirror-3x-ui/internal/util/wirecodec/wirecodec_test.go
T
Sanaei 267379456a chore(wirecodec): pin the node encoder's retained-memory budget
Two of the three options that bound the encoder had no test. With the
worker cap removed, or zstd's low-memory mode dropped, every test stayed
green while an encoder built for 64 CPUs retained 154 MiB or 13.7 MiB
instead of 9.1 MiB. Only the 1 MiB window was pinned, through the frame
header.

Build the encoder in newEncoder(cpus) so a test can size it for a
many-core host whatever machine runs it, warm every pooled workspace and
fail above 12 MiB.
2026-11-30 23:20:38 +03:30

178 lines
4.9 KiB
Go

package wirecodec
import (
"bytes"
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/klauspost/compress/zstd"
)
func TestCompressRoundTrip(t *testing.T) {
orig := []byte(strings.Repeat("inbound config payload ", 200))
packed := Compress(orig)
if len(packed) == 0 {
t.Fatal("Compress returned empty output")
}
got, err := Decompress(packed, 1<<20)
if err != nil {
t.Fatalf("Decompress: %v", err)
}
if !bytes.Equal(got, orig) {
t.Fatal("round trip mismatch")
}
}
func TestDecompressRejectsOversize(t *testing.T) {
orig := bytes.Repeat([]byte("A"), 1<<16) // 64 KiB, highly compressible
packed := Compress(orig)
if _, err := Decompress(packed, 1024); err == nil {
t.Fatal("Decompress must reject output that exceeds the cap (bomb guard)")
}
}
func TestDecompressRejectsGarbage(t *testing.T) {
if _, err := Decompress([]byte("not a zstd frame"), 1<<20); err == nil {
t.Fatal("Decompress must reject non-zstd input")
}
}
func TestSha256HexStableAndSensitive(t *testing.T) {
a := Sha256Hex([]byte("config-A"))
b := Sha256Hex([]byte("config-A"))
c := Sha256Hex([]byte("config-B"))
if a != b {
t.Fatal("hash must be stable for identical input")
}
if a == c {
t.Fatal("hash must differ when the body changes")
}
if len(a) != 64 {
t.Fatalf("expected 64 hex chars, got %d", len(a))
}
}
// Every extra frame made the decoder copy all output so far into a larger buffer, so a
// few KiB of tiny frames cost gigabytes of allocation for one authenticated request.
func TestDecompressOfManyFramesAllocatesTheOutputOnce(t *testing.T) {
frame := Compress(bytes.Repeat([]byte("A"), 4096))
src := bytes.Repeat(frame, 2000)
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
_, _ = Decompress(src, 8<<20)
runtime.ReadMemStats(&after)
if allocated := after.TotalAlloc - before.TotalAlloc; allocated > 64<<20 {
t.Fatalf("decoding %d bytes of frames allocated %d MiB", len(src), allocated>>20)
}
}
// The encoder keeps every workspace it has used for the life of the process, so
// their total must not grow with the master's CPU count (#7274).
func TestEncoderWorkspacesStayWithinBudgetOnAManyCoreHost(t *testing.T) {
const cpus, budget = 64, 12 << 20
payload := bytes.Repeat([]byte("synthetic client traffic row "), 20_000)
enc, _ := newEncoder(cpus)
defer enc.Close()
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
// EncodeAll hands the workspaces out in rotation, so sequential calls warm each one.
for range 2 * cpus {
enc.EncodeAll(payload, nil)
}
runtime.GC()
runtime.ReadMemStats(&after)
if retained := int64(after.HeapAlloc) - int64(before.HeapAlloc); retained > budget {
t.Fatalf("encoder for %d CPUs retains %.1f MiB after use, want at most %d MiB",
cpus, float64(retained)/(1<<20), budget>>20)
}
}
func TestCompressBoundsFrameWindow(t *testing.T) {
orig := bytes.Repeat([]byte("synthetic node configuration"), 150_000)
packed := Compress(orig)
var header zstd.Header
if err := header.Decode(packed); err != nil {
t.Fatal(err)
}
window := header.WindowSize
if header.SingleSegment {
window = header.FrameContentSize
}
if window > 1<<20 {
t.Fatalf("zstd frame needs %d bytes of window, want at most 1 MiB", window)
}
}
func TestCompressConcurrentFramesAreCompatible(t *testing.T) {
decoder, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1))
if err != nil {
t.Fatal(err)
}
defer decoder.Close()
var callers sync.WaitGroup
for i := range 16 {
callers.Go(func() {
raw := bytes.Repeat(fmt.Appendf(nil, "client-%d", i), 40_000)
packed, err := CompressContext(t.Context(), raw)
if err != nil {
t.Errorf("encode %d: %v", i, err)
return
}
got, err := decoder.DecodeAll(packed, nil)
if err != nil || !bytes.Equal(got, raw) {
t.Errorf("decode frame %d with the default decoder: %v", i, err)
}
})
}
callers.Wait()
encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1))
if err != nil {
t.Fatal(err)
}
defer encoder.Close()
raw := bytes.Repeat([]byte("legacy envelope"), 300_000)
decoded, err := Decompress(encoder.EncodeAll(raw, nil), len(raw))
if err != nil || !bytes.Equal(decoded, raw) {
t.Fatalf("decode frame with the legacy default window: %v", err)
}
}
func TestCompressCancelsWhileWaitingForAnEncoder(t *testing.T) {
for range cap(encoderSlots) {
encoderSlots <- struct{}{}
}
defer func() {
for range cap(encoderSlots) {
<-encoderSlots
}
}()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
called := make(chan struct{})
result := make(chan error, 1)
go func() {
close(called)
_, err := CompressContext(ctx, []byte("waiting for a slot"))
result <- err
}()
<-called
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("compression returned %v, want context.Canceled", err)
}
case <-time.After(time.Second):
t.Fatal("compression waited for a slot after cancellation")
}
}