|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// Copyright 2017 gRPC authors |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package internal // import "go.opentelemetry.io/collector/config/configgrpc/internal" |
| 6 | + |
| 7 | +import ( |
| 8 | + "errors" |
| 9 | + "io" |
| 10 | + "sync" |
| 11 | + |
| 12 | + "github.com/klauspost/compress/zstd" |
| 13 | + "google.golang.org/grpc/encoding" |
| 14 | +) |
| 15 | + |
| 16 | +const ZstdName = "zstd" |
| 17 | + |
| 18 | +func init() { |
| 19 | + encoding.RegisterCompressor(NewZstdCodec()) |
| 20 | +} |
| 21 | + |
| 22 | +type writer struct { |
| 23 | + *zstd.Encoder |
| 24 | + pool *sync.Pool |
| 25 | +} |
| 26 | + |
| 27 | +func NewZstdCodec() encoding.Compressor { |
| 28 | + c := &compressor{} |
| 29 | + c.poolCompressor.New = func() any { |
| 30 | + zw, _ := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1), zstd.WithWindowSize(512*1024)) |
| 31 | + return &writer{Encoder: zw, pool: &c.poolCompressor} |
| 32 | + } |
| 33 | + return c |
| 34 | +} |
| 35 | + |
| 36 | +func (c *compressor) Compress(w io.Writer) (io.WriteCloser, error) { |
| 37 | + z := c.poolCompressor.Get().(*writer) |
| 38 | + z.Encoder.Reset(w) |
| 39 | + return z, nil |
| 40 | +} |
| 41 | + |
| 42 | +func (z *writer) Close() error { |
| 43 | + defer z.pool.Put(z) |
| 44 | + return z.Encoder.Close() |
| 45 | +} |
| 46 | + |
| 47 | +type reader struct { |
| 48 | + *zstd.Decoder |
| 49 | + pool *sync.Pool |
| 50 | +} |
| 51 | + |
| 52 | +func (c *compressor) Decompress(r io.Reader) (io.Reader, error) { |
| 53 | + z, inPool := c.poolDecompressor.Get().(*reader) |
| 54 | + if !inPool { |
| 55 | + newZ, err := zstd.NewReader(r) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + return &reader{Decoder: newZ, pool: &c.poolDecompressor}, nil |
| 60 | + } |
| 61 | + if err := z.Reset(r); err != nil { |
| 62 | + c.poolDecompressor.Put(z) |
| 63 | + return nil, err |
| 64 | + } |
| 65 | + return z, nil |
| 66 | +} |
| 67 | + |
| 68 | +func (z *reader) Read(p []byte) (n int, err error) { |
| 69 | + n, err = z.Decoder.Read(p) |
| 70 | + if errors.Is(err, io.EOF) { |
| 71 | + z.pool.Put(z) |
| 72 | + } |
| 73 | + return n, err |
| 74 | +} |
| 75 | + |
| 76 | +func (c *compressor) Name() string { |
| 77 | + return ZstdName |
| 78 | +} |
| 79 | + |
| 80 | +type compressor struct { |
| 81 | + poolCompressor sync.Pool |
| 82 | + poolDecompressor sync.Pool |
| 83 | +} |
0 commit comments