|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package persistentqueue // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal/persistentqueue" |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "encoding/binary" |
| 9 | + "slices" |
| 10 | + |
| 11 | + "go.opentelemetry.io/otel/propagation" |
| 12 | + |
| 13 | + "go.opentelemetry.io/collector/featuregate" |
| 14 | +) |
| 15 | + |
| 16 | +// persistRequestContextFeatureGate controls whether request context should be persisted in the queue. |
| 17 | +var persistRequestContextFeatureGate = featuregate.GlobalRegistry().MustRegister( |
| 18 | + "exporter.PersistRequestContext", |
| 19 | + featuregate.StageAlpha, |
| 20 | + featuregate.WithRegisterFromVersion("v0.128.0"), |
| 21 | + featuregate.WithRegisterDescription("controls whether context should be stored alongside requests in the persistent queue"), |
| 22 | + featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector/pull/12934"), |
| 23 | +) |
| 24 | + |
| 25 | +type Encoding[T any] interface { |
| 26 | + // MarshalTo marshals a request into a preallocated byte slice. |
| 27 | + // The size of the byte slice must be at least MarshalSize(T) bytes. |
| 28 | + MarshalTo(T, []byte) (int, error) |
| 29 | + |
| 30 | + // MarshalSize returns the size of the marshaled request. |
| 31 | + MarshalSize(T) int |
| 32 | + |
| 33 | + // Unmarshal unmarshals bytes into a request. |
| 34 | + Unmarshal([]byte) (T, error) |
| 35 | +} |
| 36 | + |
| 37 | +// Encoder provides an interface for marshalling and unmarshaling requests along with their context. |
| 38 | +type Encoder[T any] struct { |
| 39 | + encoding Encoding[T] |
| 40 | +} |
| 41 | + |
| 42 | +func NewEncoder[T any](encoding Encoding[T]) Encoder[T] { |
| 43 | + return Encoder[T]{ |
| 44 | + encoding: encoding, |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +const ( |
| 49 | + // requestDataKey is the key used to store request data in bytesMap. |
| 50 | + requestDataKey = "request_data" |
| 51 | + |
| 52 | + // traceContextBufCap is a capacity of the bytesMap buffer that is enough for trace context key-value pairs. |
| 53 | + traceContextBufCap = 128 |
| 54 | +) |
| 55 | + |
| 56 | +var tracePropagator = propagation.TraceContext{} |
| 57 | + |
| 58 | +func (re Encoder[T]) Marshal(ctx context.Context, req T) ([]byte, error) { |
| 59 | + reqSize := re.encoding.MarshalSize(req) |
| 60 | + |
| 61 | + if !persistRequestContextFeatureGate.IsEnabled() { |
| 62 | + b := make([]byte, reqSize) |
| 63 | + _, err := re.encoding.MarshalTo(req, b) |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + return b, nil |
| 68 | + } |
| 69 | + |
| 70 | + bm := newBytesMap(traceContextBufCap + reqSize) |
| 71 | + tracePropagator.Inject(ctx, &bytesMapCarrier{bytesMap: *bm}) |
| 72 | + reqBuf := bm.setEmptyBytes(requestDataKey, reqSize) |
| 73 | + _, err := re.encoding.MarshalTo(req, reqBuf) |
| 74 | + if err != nil { |
| 75 | + return nil, err |
| 76 | + } |
| 77 | + |
| 78 | + return reqBuf, nil |
| 79 | +} |
| 80 | + |
| 81 | +func (re Encoder[T]) Unmarshal(b []byte) (T, context.Context, error) { |
| 82 | + if !persistRequestContextFeatureGate.IsEnabled() { |
| 83 | + req, err := re.encoding.Unmarshal(b) |
| 84 | + return req, context.Background(), err |
| 85 | + } |
| 86 | + |
| 87 | + bm := bytesMapFromBytes(b) |
| 88 | + if bm == nil { |
| 89 | + // fall back to unmarshalling of the request alone |
| 90 | + // this can happen if the data stored by old version |
| 91 | + req, err := re.encoding.Unmarshal(b) |
| 92 | + return req, context.Background(), err |
| 93 | + } |
| 94 | + ctx := context.Background() |
| 95 | + tracePropagator.Extract(ctx, &bytesMapCarrier{bytesMap: *bm}) |
| 96 | + reqBuf := bm.get(requestDataKey) |
| 97 | + req, err := re.encoding.Unmarshal(reqBuf) |
| 98 | + return req, ctx, err |
| 99 | +} |
| 100 | + |
| 101 | +// bytesMap is a slice of bytes that represents a map-like structure for storing key-value pairs. |
| 102 | +// It's optimized for efficient memory usage for low number of key-value pairs with big values. |
| 103 | +// The format is a sequence of key-value pairs encoded as: |
| 104 | +// - 1 byte length of the key |
| 105 | +// - key bytes |
| 106 | +// - 4 byte length of the value |
| 107 | +// - value bytes |
| 108 | +type bytesMap []byte |
| 109 | + |
| 110 | +// prefix bytes to denote the bytesMap serialization. |
| 111 | +const ( |
| 112 | + magicByte = byte(0x00) |
| 113 | + formatV1Byte = byte(0x01) |
| 114 | + prefixBytesLen = 2 |
| 115 | +) |
| 116 | + |
| 117 | +func newBytesMap(initSize int) *bytesMap { |
| 118 | + bm := bytesMap(make([]byte, 0, prefixBytesLen+initSize)) |
| 119 | + bm = append(bm, magicByte, formatV1Byte) |
| 120 | + return &bm |
| 121 | +} |
| 122 | + |
| 123 | +// setEmptyBytes sets the specified key in the map, reserves the given number of bytes for the value, |
| 124 | +// and returns a byte slice for the value. Must be called only once for each key. |
| 125 | +func (bm *bytesMap) setEmptyBytes(key string, size int) []byte { |
| 126 | + *bm = append(*bm, byte(len(key))) |
| 127 | + *bm = append(*bm, key...) |
| 128 | + |
| 129 | + var lenBuf [4]byte |
| 130 | + binary.LittleEndian.PutUint32(lenBuf[:], uint32(size)) |
| 131 | + *bm = append(*bm, lenBuf[:]...) |
| 132 | + |
| 133 | + start := len(*bm) |
| 134 | + *bm = slices.Grow(*bm, size) |
| 135 | + *bm = []byte(*bm)[:start+size] |
| 136 | + |
| 137 | + return []byte(*bm)[start:] |
| 138 | +} |
| 139 | + |
| 140 | +// get scans sequentially for the first matching key and returns the value as bytes. |
| 141 | +func (bm *bytesMap) get(k string) []byte { |
| 142 | + for i := prefixBytesLen; i < len(*bm); { |
| 143 | + kl := int([]byte(*bm)[i]) |
| 144 | + i++ |
| 145 | + |
| 146 | + key := string([]byte(*bm)[i : i+kl]) |
| 147 | + i += kl |
| 148 | + |
| 149 | + if i+4 > len(*bm) { |
| 150 | + return nil // malformed entry |
| 151 | + } |
| 152 | + vLen := binary.LittleEndian.Uint32([]byte(*bm)[i:]) |
| 153 | + i += 4 |
| 154 | + |
| 155 | + val := []byte(*bm)[i : i+int(vLen)] |
| 156 | + i += int(vLen) |
| 157 | + |
| 158 | + if key == k { |
| 159 | + return val |
| 160 | + } |
| 161 | + } |
| 162 | + return nil |
| 163 | +} |
| 164 | + |
| 165 | +// keys returns header names in encounter order. |
| 166 | +func (bm *bytesMap) keys() []string { |
| 167 | + var out []string |
| 168 | + for i := prefixBytesLen; i < len(*bm); { |
| 169 | + kl := int([]byte(*bm)[i]) |
| 170 | + i++ |
| 171 | + out = append(out, string([]byte(*bm)[i:i+kl])) |
| 172 | + i += kl |
| 173 | + |
| 174 | + if i+4 > len(*bm) { |
| 175 | + break |
| 176 | + } |
| 177 | + vLen := binary.LittleEndian.Uint32([]byte(*bm)[i:]) |
| 178 | + i += 4 + int(vLen) |
| 179 | + } |
| 180 | + return out |
| 181 | +} |
| 182 | + |
| 183 | +func (bm *bytesMap) bytes() []byte { return *bm } |
| 184 | + |
| 185 | +func bytesMapFromBytes(b []byte) *bytesMap { |
| 186 | + if len(b) < prefixBytesLen || b[0] != magicByte || b[1] != formatV1Byte { |
| 187 | + return nil |
| 188 | + } |
| 189 | + return (*bytesMap)(&b) |
| 190 | +} |
| 191 | + |
| 192 | +// bytesMapCarrier implements propagation.TextMapCarrier on top of bytesMap. |
| 193 | +type bytesMapCarrier struct { |
| 194 | + bytesMap |
| 195 | +} |
| 196 | + |
| 197 | +var _ propagation.TextMapCarrier = (*bytesMapCarrier)(nil) |
| 198 | + |
| 199 | +// Set appends a new string entry; if the key already exists it is left unchanged. |
| 200 | +func (c *bytesMapCarrier) Set(k, v string) { |
| 201 | + buf := c.setEmptyBytes(k, len(v)) |
| 202 | + copy(buf, v) |
| 203 | +} |
| 204 | + |
| 205 | +// Get scans sequentially for the first matching key. |
| 206 | +func (c *bytesMapCarrier) Get(k string) string { |
| 207 | + return string(c.get(k)) // returns string value |
| 208 | +} |
| 209 | + |
| 210 | +// Keys returns header names in encounter order. |
| 211 | +func (c *bytesMapCarrier) Keys() []string { |
| 212 | + return c.keys() |
| 213 | +} |
0 commit comments