| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package request // import "go.opentelemetry.io/collector/pdata/xpdata/request" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
|
| 10 |
"go.opentelemetry.io/collector/pdata/internal" |
| 11 |
"go.opentelemetry.io/collector/pdata/pmetric" |
| 12 |
) |
| 13 |
|
| 14 |
// MarshalMetrics marshals pmetric.Metrics along with the context into a byte slice. |
| 15 |
func MarshalMetrics(ctx context.Context, ld pmetric.Metrics) ([]byte, error) { |
| 16 |
mr := internal.MetricsRequest{ |
| 17 |
FormatVersion: requestFormatVersion, |
| 18 |
MetricsData: internal.MetricsToProto(internal.MetricsWrapper(ld)), |
| 19 |
RequestContext: encodeContext(ctx), |
| 20 |
} |
| 21 |
buf := make([]byte, mr.SizeProto()) |
| 22 |
mr.MarshalProto(buf) |
| 23 |
return buf, nil |
| 24 |
} |
| 25 |
|
| 26 |
// UnmarshalMetrics unmarshals a byte slice into pmetric.Metrics and the context. |
| 27 |
func UnmarshalMetrics(buf []byte) (context.Context, pmetric.Metrics, error) { |
| 28 |
ctx := context.Background() |
| 29 |
if !isRequestPayloadV1(buf) { |
| 30 |
return ctx, pmetric.Metrics{}, ErrInvalidFormat |
| 31 |
} |
| 32 |
mr := internal.MetricsRequest{} |
| 33 |
if err := mr.UnmarshalProto(buf); err != nil { |
| 34 |
return ctx, pmetric.Metrics{}, fmt.Errorf("failed to unmarshal metrics request: %w", err) |
| 35 |
} |
| 36 |
return decodeContext(ctx, mr.RequestContext), pmetric.Metrics(internal.MetricsFromProto(mr.MetricsData)), nil |
| 37 |
} |