use smallzstd and sync pool

This commit is contained in:
Johan Siebens 2023-01-02 07:48:30 +01:00 committed by Juan Font
parent 6d669c6b9c
commit e128796b59
3 changed files with 30 additions and 4 deletions

View file

@ -3,9 +3,11 @@ package headscale
import (
"encoding/binary"
"encoding/json"
"sync"
"github.com/klauspost/compress/zstd"
"github.com/rs/zerolog/log"
"tailscale.com/smallzstd"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
@ -103,8 +105,7 @@ func (h *Headscale) marshalMapResponse(
var respBody []byte
if compression == ZstdCompression {
encoder, _ := zstd.NewWriter(nil)
respBody = encoder.EncodeAll(jsonBody, nil)
respBody = zstdEncode(jsonBody)
if !isNoise { // if legacy protocol
respBody = h.privateKey.SealTo(machineKey, respBody)
}
@ -122,3 +123,28 @@ func (h *Headscale) marshalMapResponse(
return data, nil
}
func zstdEncode(in []byte) []byte {
encoder, ok := zstdEncoderPool.Get().(*zstd.Encoder)
if !ok {
panic("invalid type in sync pool")
}
out := encoder.EncodeAll(in, nil)
_ = encoder.Close()
zstdEncoderPool.Put(encoder)
return out
}
var zstdEncoderPool = &sync.Pool{
New: func() any {
encoder, err := smallzstd.NewEncoder(
nil,
zstd.WithEncoderLevel(zstd.SpeedFastest))
if err != nil {
panic(err)
}
return encoder
},
}