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") } }