Files
mirror-3x-ui/internal/util/wirecodec/wirecodec.go
T
Hamed Sanaei bd8648de73 perf(wirecodec): bound node envelope compression memory (#7275)
The shared zstd encoder for master-to-node request bodies was built with
library defaults: one workspace per CPU, each holding a 16 MiB history for
the default 8 MiB window. The pool hands its workspaces out in rotation and
never frees them, so a 4-vCPU master kept about 70 MiB alive after its
first few pushes and a 16-core one about 280 MiB.

Build it with a 1 MiB window, at most four workers and zstd's low-memory
mode, which retains about 10 MiB whatever the CPU count. Callers queue for
a worker on a slot channel, so a cancelled push stops waiting instead of
blocking inside EncodeAll. Frames stay standard zstd: capability
negotiation, the SHA-256 of the uncompressed body and the node's decode
bounds are unchanged.

Closes #7274
2026-11-30 23:16:52 +03:30

121 lines
4.4 KiB
Go

// Package wirecodec holds the shared envelope codec for node-to-node config
// transport: zstd (de)compression, SHA-256 integrity hashing, and the header /
// capability constants both the panel (sender) and node (receiver) agree on.
package wirecodec
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"runtime"
"github.com/klauspost/compress/zstd"
)
const (
// HashHeader carries the lowercase-hex SHA-256 of the (uncompressed) body.
HashHeader = "X-Config-Sha256"
// CapsHeader is set by a node on its API responses to advertise support.
CapsHeader = "X-3x-Node-Caps"
// MasterPushHeader marks a request as a master's push, whatever its token scope.
MasterPushHeader = "X-3x-Master-Push"
// EncodingZstd is the Content-Encoding value for a zstd-compressed body.
EncodingZstd = "zstd"
// CapZstd is the capability token advertised in CapsHeader.
CapZstd = "zstd"
// CapAmneziaWGKernel marks a node that honours an AmneziaWG inbound's
// kernelMode; an older node drops the flag and serves it embedded.
CapAmneziaWGKernel = "awg-kernel"
// CapPreserveClientTraffic marks a node that supports inbound-only scheduled resets.
CapPreserveClientTraffic = "preserve-client-traffic"
// CapWireguardDevices marks a node that serves a WireGuard client's extra devices;
// an older node ignores them and keeps only the client's first peer.
CapWireguardDevices = "wg-devices"
// CapTrafficSnapshot marks a node that serves revisioned traffic snapshots.
CapTrafficSnapshot = "traffic-snapshot-v1"
// NodeCaps is the full CapsHeader value this build advertises.
NodeCaps = CapZstd + "," + CapAmneziaWGKernel + "," + CapPreserveClientTraffic + "," + CapWireguardDevices + "," + CapTrafficSnapshot
// maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from
// an (authenticated) node-API caller.
maxDecodeBytes = 16 << 20
// Node requests reuse a small history and keep a fixed upper bound on
// retained encoder workspaces, even on a master with many CPUs.
encoderWindow = 1 << 20
maxEncoderWorkers = 4
)
// EncodeAll/DecodeAll on these shared instances are safe for concurrent use.
var (
encoderWorkers = min(maxEncoderWorkers, runtime.GOMAXPROCS(0))
encoderSlots = make(chan struct{}, encoderWorkers)
zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow),
zstd.WithEncoderConcurrency(encoderWorkers), zstd.WithLowerEncoderMem(true))
decoderWorkers = runtime.GOMAXPROCS(0)
zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes),
zstd.WithDecodeAllCapLimit(true), zstd.WithDecoderConcurrency(decoderWorkers))
// decodeSlots keeps callers waiting for a decoder worker from each holding an output buffer.
decodeSlots = make(chan struct{}, decoderWorkers)
errDecodedTooLarge = errors.New("wirecodec: decompressed body exceeds limit")
)
// Compress zstd-compresses b.
func Compress(b []byte) []byte {
out, _ := CompressContext(context.Background(), b)
return out
}
// CompressContext lets a caller cancel while waiting for an encoder. Once
// EncodeAll starts it runs synchronously.
func CompressContext(ctx context.Context, b []byte) ([]byte, error) {
select {
case encoderSlots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-encoderSlots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return zstdEncoder.EncodeAll(b, nil), nil
}
// Decompress zstd-decompresses src, rejecting output larger than maxOut (and any
// input that would blow the in-memory bomb ceiling).
func Decompress(src []byte, maxOut int) ([]byte, error) {
if maxOut <= 0 || maxOut > maxDecodeBytes {
maxOut = maxDecodeBytes
}
var header zstd.Header
if err := header.Decode(src); err != nil {
return nil, err
}
// The output buffer is sized once, from the first frame (Compress writes a single
// frame): letting it grow per frame copied all output so far for every extra frame.
size := maxOut
if header.HasFCS {
if header.FrameContentSize > uint64(maxOut) {
return nil, errDecodedTooLarge
}
size = int(header.FrameContentSize)
}
decodeSlots <- struct{}{}
defer func() { <-decodeSlots }()
out, err := zstdDecoder.DecodeAll(src, make([]byte, 0, size))
if errors.Is(err, zstd.ErrDecoderSizeExceeded) {
return nil, errDecodedTooLarge
}
if err != nil {
return nil, err
}
return out, nil
}
// Sha256Hex returns the lowercase-hex SHA-256 of b.
func Sha256Hex(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}