CodeSampleX

Exemplo

go.opentelemetry.io/proto/otlp v1.9.0: MetricsData

Amostra verificada para golang go.opentelemetry.io/proto/otlp v1.9.0: MetricsData. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:b4596e2d682215998bb3976b49d555ffb5a0511d34d1855beb6070f987f0c127

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-05

Caso

HOW
Objetivo
verify MetricsData in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Pacotes
Símbolos
  • MetricsData
Ambiente
go
Criado
2026-09-05T09:31:30Z

Contrato

  1. MetricsData constructs and holds valid ResourceMetrics with Resource, ScopeMetrics, and Metric records
  2. MetricsData supports Gauge and Sum metrics with typed number data points
  3. MetricsData marshals to and unmarshals from binary protobuf wire format without data loss
  4. MetricsData marshals to and unmarshals from JSON format preserving metric attributes and metadata
  5. MetricsData preserves aggregation temporality and monotonicity flags across serialization
  6. MetricsData handles multiple ResourceMetrics with distinct instrumentation scopes and timestamps

Arquivos

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify MetricsData in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0
Demonstrate these symbols/APIs:
  - MetricsData

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
contract_test.go
package sample

import (
	"bytes"
	"strings"
	"testing"

	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
)

func TestMetricsDataContract(t *testing.T) {
	// 1. MetricsData constructs and holds valid ResourceMetrics with Resource, ScopeMetrics, and Metric records
	t.Run("ConstructValidMetricsData", func(t *testing.T) {
		dp := NewNumberDataPointDouble(1700000000000000000, 1699999990000000000, 42.5, StringAttribute("cpu.core", "0"))
		metric := NewGaugeMetric("system.cpu.load", "Current CPU load percentage", "%", []*metricspb.NumberDataPoint{dp})
		scopeMetrics := NewScopeMetrics("sample/metric-generator", "1.0.0", []*metricspb.Metric{metric})
		resMetrics := NewResourceMetrics("telemetry-service", []*metricspb.ScopeMetrics{scopeMetrics})
		metricsData := NewMetricsData(resMetrics)

		if len(metricsData.GetResourceMetrics()) != 1 {
			t.Fatalf("expected 1 ResourceMetrics, got %d", len(metricsData.GetResourceMetrics()))
		}
		rm := metricsData.GetResourceMetrics()[0]
		if rm.GetResource() == nil || len(rm.GetResource().GetAttributes()) == 0 {
			t.Fatalf("expected resource attributes to be present")
		}
		if rm.GetResource().GetAttributes()[0].GetKey() != "service.name" ||
			rm.GetResource().GetAttributes()[0].GetValue().GetStringValue() != "telemetry-service" {
			t.Fatalf("unexpected resource attribute: %v", rm.GetResource().GetAttributes()[0])
		}
		if len(rm.GetScopeMetrics()) != 1 {
			t.Fatalf("expected 1 ScopeMetrics, got %d", len(rm.GetScopeMetrics()))
		}
		sm := rm.GetScopeMetrics()[0]
		if sm.GetScope().GetName() != "sample/metric-generator" || sm.GetScope().GetVersion() != "1.0.0" {
			t.Fatalf("unexpected scope: %v", sm.GetScope())
		}
		if len(sm.GetMetrics()) != 1 {
			t.Fatalf("expected 1 Metric, got %d", len(sm.GetMetrics()))
		}
		m := sm.GetMetrics()[0]
		if m.GetName() != "system.cpu.load" || m.GetUnit() != "%" {
			t.Fatalf("unexpected metric metadata: name=%q unit=%q", m.GetName(), m.GetUnit())
		}
	})

	// 2. MetricsData supports Gauge and Sum metrics with typed number data points
	t.Run("GaugeAndSumMetricsSupport", func(t *testing.T) {
		gaugeDp := NewNumberDataPointDouble(1700000000000000000, 0, 78.4, StringAttribute("host.name", "worker-1"))
		gaugeMetric := NewGaugeMetric("process.memory.usage_mb", "Memory usage in megabytes", "MB", []*metricspb.NumberDataPoint{gaugeDp})

		sumDp := NewNumberDataPointInt(1700000000000000000, 1699999000000000000, 1500, StringAttribute("http.status", "200"))
		sumMetric := NewSumMetric(
			"http.server.request_count",
			"Total processed HTTP requests",
			"requests",
			true,
			metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
			[]*metricspb.NumberDataPoint{sumDp},
		)

		scopeMetrics := NewScopeMetrics("sample/meter", "1.2.0", []*metricspb.Metric{gaugeMetric, sumMetric})
		resMetrics := NewResourceMetrics("api-gateway", []*metricspb.ScopeMetrics{scopeMetrics})
		metricsData := NewMetricsData(resMetrics)

		metrics := metricsData.GetResourceMetrics()[0].GetScopeMetrics()[0].GetMetrics()
		if len(metrics) != 2 {
			t.Fatalf("expected 2 metrics, got %d", len(metrics))
		}

		// Check Gauge
		gauge := metrics[0].GetGauge()
		if gauge == nil || len(gauge.GetDataPoints()) != 1 {
			t.Fatalf("expected Gauge data points")
		}
		if gauge.GetDataPoints()[0].GetAsDouble() != 78.4 {
			t.Fatalf("expected double value 78.4, got %f", gauge.GetDataPoints()[0].GetAsDouble())
		}

		// Check Sum
		sum := metrics[1].GetSum()
		if sum == nil || len(sum.GetDataPoints()) != 1 {
			t.Fatalf("expected Sum data points")
		}
		if sum.GetDataPoints()[0].GetAsInt() != 1500 {
			t.Fatalf("expected int value 1500, got %d", sum.GetDataPoints()[0].GetAsInt())
		}
		if !sum.GetIsMonotonic() {
			t.Fatalf("expected monotonic sum metric")
		}
		if sum.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE {
			t.Fatalf("expected cumulative temporality")
		}
	})

	// 3. MetricsData marshals to and unmarshals from binary protobuf wire format without data loss
	t.Run("ProtobufSerializationRoundtrip", func(t *testing.T) {
		dp := NewNumberDataPointInt(
			1700000000000000000,
			1699999000000000000,
			2048,
			StringAttribute("region", "us-central1"),
			IntAttribute("node.id", 42),
			BoolAttribute("active", true),
			DoubleAttribute("ratio", 0.99),
			BytesAttribute("checksum", []byte{0xca, 0xfe, 0xba, 0xbe}),
		)
		metric := NewGaugeMetric("cache.entries", "Number of cache entries", "entries", []*metricspb.NumberDataPoint{dp})
		scopeMetrics := NewScopeMetrics("sample/cache-meter", "2.0.0", []*metricspb.Metric{metric})
		resMetrics := NewResourceMetrics("cache-cluster", []*metricspb.ScopeMetrics{scopeMetrics})
		metricsData := NewMetricsData(resMetrics)

		data, err := MarshalProto(metricsData)
		if err != nil {
			t.Fatalf("failed to marshal metrics data to protobuf: %v", err)
		}
		if len(data) == 0 {
			t.Fatalf("marshaled protobuf wire format is empty")
		}

		unmarshaled, err := UnmarshalProto(data)
		if err != nil {
			t.Fatalf("failed to unmarshal metrics data from protobuf: %v", err)
		}
		if len(unmarshaled.GetResourceMetrics()) != 1 {
			t.Fatalf("expected 1 ResourceMetrics after unmarshal, got %d", len(unmarshaled.GetResourceMetrics()))
		}
		uMetric := unmarshaled.GetResourceMetrics()[0].GetScopeMetrics()[0].GetMetrics()[0]
		if uMetric.GetName() != "cache.entries" {
			t.Fatalf("metric name mismatch: got %q, want 'cache.entries'", uMetric.GetName())
		}
		uPoint := uMetric.GetGauge().GetDataPoints()[0]
		if uPoint.GetAsInt() != 2048 {
			t.Fatalf("metric point value mismatch: got %d, want 2048", uPoint.GetAsInt())
		}
		if uPoint.GetTimeUnixNano() != 1700000000000000000 {
			t.Fatalf("timestamp mismatch: got %d, want 1700000000000000000", uPoint.GetTimeUnixNano())
		}
		if uPoint.GetStartTimeUnixNano() != 1699999000000000000 {
			t.Fatalf("start timestamp mismatch: got %d, want 1699999000000000000", uPoint.GetStartTimeUnixNano())
		}
		attrs := uPoint.GetAttributes()
		if len(attrs) != 5 {
			t.Fatalf("expected 5 attributes, got %d", len(attrs))
		}
		if attrs[0].GetKey() != "region" || attrs[0].GetValue().GetStringValue() != "us-central1" {
			t.Fatalf("attribute mismatch: %v", attrs[0])
		}
		if !bytes.Equal(attrs[4].GetValue().GetBytesValue(), []byte{0xca, 0xfe, 0xba, 0xbe}) {
			t.Fatalf("bytes attribute mismatch: %v", attrs[4])
		}
	})

	// 4. MetricsData marshals to and unmarshals from JSON format preserving metric attributes and metadata
	t.Run("JSONSerializationRoundtrip", func(t *testing.T) {
		dp := NewNumberDataPointDouble(1700000000000000000, 0, 99.9, StringAttribute("tier", "frontend"))
		metric := NewGaugeMetric("uptime.percentage", "Uptime percentage", "%", []*metricspb.NumberDataPoint{dp})
		scopeMetrics := NewScopeMetrics("sample/json-meter", "1.0.0", []*metricspb.Metric{metric})
		resMetrics := NewResourceMetrics("web-portal", []*metricspb.ScopeMetrics{scopeMetrics})
		metricsData := NewMetricsData(resMetrics)

		jsonData, err := MarshalJSON(metricsData)
		if err != nil {
			t.Fatalf("failed to marshal metrics data to JSON: %v", err)
		}
		jsonStr := string(jsonData)
		if !strings.Contains(jsonStr, "web-portal") || !strings.Contains(jsonStr, "uptime.percentage") {
			t.Fatalf("JSON output missing expected tokens: %s", jsonStr)
		}

		unmarshaled, err := UnmarshalJSON(jsonData)
		if err != nil {
			t.Fatalf("failed to unmarshal metrics data from JSON: %v", err)
		}
		if len(unmarshaled.GetResourceMetrics()) != 1 {
			t.Fatalf("unmarshaled JSON missing ResourceMetrics")
		}
		uMetric := unmarshaled.GetResourceMetrics()[0].GetScopeMetrics()[0].GetMetrics()[0]
		if uMetric.GetName() != "uptime.percentage" {
			t.Fatalf("unmarshaled JSON metric name mismatch: got %q, want 'uptime.percentage'", uMetric.GetName())
		}
		if uMetric.GetGauge().GetDataPoints()[0].GetAsDouble() != 99.9 {
			t.Fatalf("unmarshaled JSON metric value mismatch: got %f, want 99.9", uMetric.GetGauge().GetDataPoints()[0].GetAsDouble())
		}
	})

	// 5. MetricsData preserves aggregation temporality and monotonicity flags across serialization
	t.Run("TemporalityAndMonotonicityPreservation", func(t *testing.T) {
		sumDp := NewNumberDataPointInt(1700000000000000000, 1699999000000000000, 350)
		metric := NewSumMetric(
			"bytes.transmitted",
			"Network bytes sent",
			"By",
			true,
			metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,
			[]*metricspb.NumberDataPoint{sumDp},
		)
		scopeMetrics := NewScopeMetrics("sample/net-meter", "1.0.0", []*metricspb.Metric{metric})
		resMetrics := NewResourceMetrics("network-daemon", []*metricspb.ScopeMetrics{scopeMetrics})
		metricsData := NewMetricsData(resMetrics)

		data, err := MarshalProto(metricsData)
		if err != nil {
			t.Fatalf("proto marshal failed: %v", err)
		}

		unmarshaled, err := UnmarshalProto(data)
		if err != nil {
			t.Fatalf("proto unmarshal failed: %v", err)
		}
		uSum := unmarshaled.GetResourceMetrics()[0].GetScopeMetrics()[0].GetMetrics()[0].GetSum()
		if !uSum.GetIsMonotonic() {
			t.Fatalf("expected is_monotonic to remain true")
		}
		if uSum.GetAggregationTemporality() != metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA {
			t.Fatalf("expected delta aggregation temporality preserved")
		}
	})

	// 6. MetricsData handles multiple ResourceMetrics with distinct instrumentation scopes and timestamps
	t.Run("MultipleResourceMetricsHandling", func(t *testing.T) {
		rm1 := NewResourceMetrics("database-primary", []*metricspb.ScopeMetrics{
			NewScopeMetrics("sample/db", "1.0.0", []*metricspb.Metric{
				NewGaugeMetric("db.connections.active", "Active connections", "conn", []*metricspb.NumberDataPoint{
					NewNumberDataPointInt(1700000001000000000, 0, 12),
				}),
			}),
		})
		rm2 := NewResourceMetrics("cache-replica", []*metricspb.ScopeMetrics{
			NewScopeMetrics("sample/cache", "1.0.0", []*metricspb.Metric{
				NewGaugeMetric("cache.hit_ratio", "Cache hit percentage", "%", []*metricspb.NumberDataPoint{
					NewNumberDataPointDouble(1700000002000000000, 0, 94.2),
				}),
			}),
		})
		multiMetrics := NewMetricsData(rm1, rm2)

		data, err := MarshalProto(multiMetrics)
		if err != nil {
			t.Fatalf("marshal multi-resource metrics failed: %v", err)
		}
		unmarshaled, err := UnmarshalProto(data)
		if err != nil {
			t.Fatalf("unmarshal multi-resource metrics failed: %v", err)
		}
		if len(unmarshaled.GetResourceMetrics()) != 2 {
			t.Fatalf("expected 2 ResourceMetrics, got %d", len(unmarshaled.GetResourceMetrics()))
		}
		rm0Name := unmarshaled.GetResourceMetrics()[0].GetResource().GetAttributes()[0].GetValue().GetStringValue()
		rm1Name := unmarshaled.GetResourceMetrics()[1].GetResource().GetAttributes()[0].GetValue().GetStringValue()
		if rm0Name != "database-primary" || rm1Name != "cache-replica" {
			t.Fatalf("service names mismatch: got %q and %q", rm0Name, rm1Name)
		}
	})
}
csx.json
{"case":{"caseId":"case:sha256:b46729ef7c1eb17a9c6485068bd770343f3842c7de73972545024c1a1656b104","contract":["MetricsData constructs and holds valid ResourceMetrics with Resource, ScopeMetrics, and Metric records","MetricsData supports Gauge and Sum metrics with typed number data points","MetricsData marshals to and unmarshals from binary protobuf wire format without data loss","MetricsData marshals to and unmarshals from JSON format preserving metric attributes and metadata","MetricsData preserves aggregation temporality and monotonicity flags across serialization","MetricsData handles multiple ResourceMetrics with distinct instrumentation scopes and timestamps"],"goal":"verify MetricsData in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"],"schemaVersion":1,"symbols":["MetricsData"]},"contractCommand":["go","test","-mod=readonly","-count=1","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0","symbols":["MetricsData"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/proto/otlp v1.9.0
	google.golang.org/protobuf v1.36.11
)
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
sample.go
package sample

import (
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

// StringAttribute creates a string KeyValue attribute.
func StringAttribute(key, value string) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_StringValue{
				StringValue: value,
			},
		},
	}
}

// IntAttribute creates an int64 KeyValue attribute.
func IntAttribute(key string, value int64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_IntValue{
				IntValue: value,
			},
		},
	}
}

// BoolAttribute creates a boolean KeyValue attribute.
func BoolAttribute(key string, value bool) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BoolValue{
				BoolValue: value,
			},
		},
	}
}

// DoubleAttribute creates a float64 KeyValue attribute.
func DoubleAttribute(key string, value float64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_DoubleValue{
				DoubleValue: value,
			},
		},
	}
}

// BytesAttribute creates a byte slice KeyValue attribute.
func BytesAttribute(key string, value []byte) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BytesValue{
				BytesValue: value,
			},
		},
	}
}

// NewNumberDataPointInt creates a NumberDataPoint with an int64 value.
func NewNumberDataPointInt(timeUnixNano, startTimeUnixNano uint64, value int64, attributes ...*commonpb.KeyValue) *metricspb.NumberDataPoint {
	return &metricspb.NumberDataPoint{
		TimeUnixNano:      timeUnixNano,
		StartTimeUnixNano: startTimeUnixNano,
		Value: &metricspb.NumberDataPoint_AsInt{
			AsInt: value,
		},
		Attributes: attributes,
	}
}

// NewNumberDataPointDouble creates a NumberDataPoint with a float64 value.
func NewNumberDataPointDouble(timeUnixNano, startTimeUnixNano uint64, value float64, attributes ...*commonpb.KeyValue) *metricspb.NumberDataPoint {
	return &metricspb.NumberDataPoint{
		TimeUnixNano:      timeUnixNano,
		StartTimeUnixNano: startTimeUnixNano,
		Value: &metricspb.NumberDataPoint_AsDouble{
			AsDouble: value,
		},
		Attributes: attributes,
	}
}

// NewGaugeMetric creates a Metric containing Gauge data points.
func NewGaugeMetric(name, description, unit string, points []*metricspb.NumberDataPoint) *metricspb.Metric {
	return &metricspb.Metric{
		Name:        name,
		Description: description,
		Unit:        unit,
		Data: &metricspb.Metric_Gauge{
			Gauge: &metricspb.Gauge{
				DataPoints: points,
			},
		},
	}
}

// NewSumMetric creates a Metric containing Sum data points with temporality and monotonicity settings.
func NewSumMetric(name, description, unit string, isMonotonic bool, temporality metricspb.AggregationTemporality, points []*metricspb.NumberDataPoint) *metricspb.Metric {
	return &metricspb.Metric{
		Name:        name,
		Description: description,
		Unit:        unit,
		Data: &metricspb.Metric_Sum{
			Sum: &metricspb.Sum{
				DataPoints:             points,
				IsMonotonic:            isMonotonic,
				AggregationTemporality: temporality,
			},
		},
	}
}

// NewScopeMetrics creates ScopeMetrics with instrumentation scope info and metrics.
func NewScopeMetrics(scopeName, scopeVersion string, metrics []*metricspb.Metric) *metricspb.ScopeMetrics {
	return &metricspb.ScopeMetrics{
		Scope: &commonpb.InstrumentationScope{
			Name:    scopeName,
			Version: scopeVersion,
		},
		Metrics: metrics,
	}
}

// NewResourceMetrics creates ResourceMetrics with service name attribute and scope metrics.
func NewResourceMetrics(serviceName string, scopeMetrics []*metricspb.ScopeMetrics) *metricspb.ResourceMetrics {
	return &metricspb.ResourceMetrics{
		Resource: &resourcepb.Resource{
			Attributes: []*commonpb.KeyValue{
				StringAttribute("service.name", serviceName),
			},
		},
		ScopeMetrics: scopeMetrics,
	}
}

// NewMetricsData wraps ResourceMetrics into a MetricsData container.
func NewMetricsData(resMetrics ...*metricspb.ResourceMetrics) *metricspb.MetricsData {
	return &metricspb.MetricsData{
		ResourceMetrics: resMetrics,
	}
}

// MarshalProto serializes MetricsData to protobuf wire format.
func MarshalProto(metrics *metricspb.MetricsData) ([]byte, error) {
	return proto.Marshal(metrics)
}

// UnmarshalProto deserializes MetricsData from protobuf wire format.
func UnmarshalProto(data []byte) (*metricspb.MetricsData, error) {
	metrics := &metricspb.MetricsData{}
	if err := proto.Unmarshal(data, metrics); err != nil {
		return nil, err
	}
	return metrics, nil
}

// MarshalJSON serializes MetricsData to JSON.
func MarshalJSON(metrics *metricspb.MetricsData) ([]byte, error) {
	return protojson.Marshal(metrics)
}

// UnmarshalJSON deserializes MetricsData from JSON.
func UnmarshalJSON(data []byte) (*metricspb.MetricsData, error) {
	metrics := &metricspb.MetricsData{}
	if err := protojson.Unmarshal(data, metrics); err != nil {
		return nil, err
	}
	return metrics, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify MetricsData in pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/proto/otlp@v1.9.0"
  ],
  "symbols": [
    "MetricsData"
  ]
}

Seeder de origem

anônimo