| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package otelgrpc // import "go.opentelemetry.io/collector/pdata/internal/otelgrpc" |
| 5 |
|
| 6 |
import ( |
| 7 |
"google.golang.org/grpc/encoding" |
| 8 |
"google.golang.org/grpc/mem" |
| 9 |
) |
| 10 |
|
| 11 |
var ( |
| 12 |
defaultBufferPoolSizes = []int{ |
| 13 |
256, |
| 14 |
4 << 10, // 4KB (go page size) |
| 15 |
16 << 10, // 16KB (max HTTP/2 frame size used by gRPC) |
| 16 |
32 << 10, // 32KB (default buffer size for io.Copy) |
| 17 |
512 << 10, // 512KB |
| 18 |
1 << 20, // 1MB |
| 19 |
4 << 20, // 4MB |
| 20 |
16 << 20, // 16MB |
| 21 |
} |
| 22 |
otelBufferPool = mem.NewTieredBufferPool(defaultBufferPoolSizes...) |
| 23 |
) |
| 24 |
|
| 25 |
// DefaultBufferPool returns the current default buffer pool. It is a BufferPool |
| 26 |
// created with mem.NewTieredBufferPool that uses a set of default sizes optimized for |
| 27 |
// expected telemetry workflows. |
| 28 |
func DefaultBufferPool() mem.BufferPool { |
| 29 |
return otelBufferPool |
| 30 |
} |
| 31 |
|
| 32 |
// Name is the name registered for the proto compressor. |
| 33 |
const Name = "proto" |
| 34 |
|
| 35 |
func init() { |
| 36 |
encoding.RegisterCodecV2(&codecV2{delegate: encoding.GetCodecV2(Name)}) |
| 37 |
} |
| 38 |
|
| 39 |
// codecV2 is a custom proto encoding that uses a different tier schema for the TieredBufferPool as well |
| 40 |
// as it call into the custom marshal/unmarshal logic that works with memory pooling. |
| 41 |
// If not an otlp payload fallback on the default grpc/proto encoding. |
| 42 |
type codecV2 struct { |
| 43 |
delegate encoding.CodecV2 |
| 44 |
} |
| 45 |
|
| 46 |
type otelEncoder interface { |
| 47 |
SizeProto() int |
| 48 |
MarshalProto([]byte) int |
| 49 |
UnmarshalProto([]byte) error |
| 50 |
} |
| 51 |
|
| 52 |
func (c *codecV2) Marshal(v any) (mem.BufferSlice, error) { |
| 53 |
if m, ok := v.(otelEncoder); ok { |
| 54 |
size := m.SizeProto() |
| 55 |
buf := otelBufferPool.Get(size) |
| 56 |
n := m.MarshalProto((*buf)[:size]) |
| 57 |
*buf = (*buf)[:n] |
| 58 |
return []mem.Buffer{mem.NewBuffer(buf, otelBufferPool)}, nil |
| 59 |
} |
| 60 |
|
| 61 |
return c.delegate.Marshal(v) |
| 62 |
} |
| 63 |
|
| 64 |
func (c *codecV2) Unmarshal(data mem.BufferSlice, v any) (err error) { |
| 65 |
if m, ok := v.(otelEncoder); ok { |
| 66 |
// TODO: Upgrade custom Unmarshal logic to support reading from mem.BufferSlice. |
| 67 |
buf := data.MaterializeToBuffer(otelBufferPool) |
| 68 |
defer buf.Free() |
| 69 |
return m.UnmarshalProto(buf.ReadOnlyData()) |
| 70 |
} |
| 71 |
|
| 72 |
return c.delegate.Unmarshal(data, v) |
| 73 |
} |
| 74 |
|
| 75 |
func (c *codecV2) Name() string { |
| 76 |
return Name |
| 77 |
} |