CodeSampleX

サンプル

go.opentelemetry.io/otel/sdk/metric v1.44.0: NewView

検証済みサンプル — golang go.opentelemetry.io/otel/sdk/metric v1.44.0: NewView. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:e33977fda3c056c1b9027779cd25959c9a747421301c177b083d325a4b6aeb8c

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
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-10-10

ケース

HOW
ゴール
verify go.opentelemetry.io/otel/sdk/metric.NewView in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0
パッケージ
シンボル
  • go.opentelemetry.io/otel/sdk/metric.NewView
作成日
2026-10-10T23:04:15Z

コントラクト

  1. metric.NewView returns a View matching instruments using wildcard name patterns
  2. metric.NewView returns false when instrument kind or other non-zero criteria do not match
  3. metric.NewView overrides stream name, description, and aggregation for matching instruments
  4. metric.NewView with empty criteria matches no instruments
  5. MeterProvider configured with NewView transforms instrument stream and filters attributes upon collection

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go
  • view.go

ソースアーティファクトをダウンロード (tar.gz)

ソース

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 go.opentelemetry.io/otel/sdk/metric.NewView in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/otel/sdk/metric.NewView

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.
csx.json
{"case":{"caseId":"case:sha256:de05401381da48366b67dc517e4d2a3948beaf712e6dfdd677c1c9dd969b0306","contract":["metric.NewView returns a View matching instruments using wildcard name patterns","metric.NewView returns false when instrument kind or other non-zero criteria do not match","metric.NewView overrides stream name, description, and aggregation for matching instruments","metric.NewView with empty criteria matches no instruments","MeterProvider configured with NewView transforms instrument stream and filters attributes upon collection"],"goal":"verify go.opentelemetry.io/otel/sdk/metric.NewView in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/sdk/metric.NewView"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0","symbols":["go.opentelemetry.io/otel/sdk/metric.NewView"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/otel v1.44.0
	go.opentelemetry.io/otel/metric v1.44.0
	go.opentelemetry.io/otel/sdk/metric v1.44.0
)

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/google/uuid v1.6.0 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel/sdk v1.44.0 // indirect
	go.opentelemetry.io/otel/trace v1.44.0 // indirect
	golang.org/x/sys v0.45.0 // indirect
)
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=
go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/sdk/metric.NewView in pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/sdk/metric@v1.44.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/sdk/metric.NewView"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"os"

	"go.opentelemetry.io/otel/attribute"
	otelmetric "go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"

	"sample"
)

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All metric.NewView contract tests passed successfully.")
}

func runContractTests() error {
	ctx := context.Background()

	// 1. metric.NewView returns a View matching instruments using wildcard name patterns
	{
		view := metric.NewView(
			metric.Instrument{Name: "http.*"},
			metric.Stream{Description: "http metrics"},
		)

		matchInst := metric.Instrument{Name: "http.server.duration"}
		stream, matched := view(matchInst)
		if !matched {
			return fmt.Errorf("expected view to match 'http.server.duration' with pattern 'http.*'")
		}
		if stream.Description != "http metrics" {
			return fmt.Errorf("expected stream description 'http metrics', got '%s'", stream.Description)
		}

		noMatchInst := metric.Instrument{Name: "db.client.duration"}
		_, matched = view(noMatchInst)
		if matched {
			return fmt.Errorf("expected view not to match 'db.client.duration' with pattern 'http.*'")
		}
	}

	// 2. metric.NewView returns false when instrument kind or other non-zero criteria do not match
	{
		view := metric.NewView(
			metric.Instrument{
				Name: "request_total",
				Kind: metric.InstrumentKindCounter,
			},
			metric.Stream{Description: "counter only"},
		)

		matchInst := metric.Instrument{
			Name: "request_total",
			Kind: metric.InstrumentKindCounter,
		}
		_, matched := view(matchInst)
		if !matched {
			return fmt.Errorf("expected view to match instrument with matching name and kind")
		}

		mismatchInst := metric.Instrument{
			Name: "request_total",
			Kind: metric.InstrumentKindHistogram,
		}
		_, matched = view(mismatchInst)
		if matched {
			return fmt.Errorf("expected view not to match instrument with different kind")
		}
	}

	// 3. metric.NewView overrides stream name, description, and aggregation for matching instruments
	{
		dropAgg := metric.AggregationDrop{}
		view := metric.NewView(
			metric.Instrument{Name: "legacy_metric"},
			metric.Stream{
				Name:        "modern_metric",
				Description: "remapped metric description",
				Aggregation: dropAgg,
			},
		)

		inst := metric.Instrument{
			Name:        "legacy_metric",
			Description: "old description",
			Unit:        "ms",
		}
		stream, matched := view(inst)
		if !matched {
			return fmt.Errorf("expected view to match 'legacy_metric'")
		}
		if stream.Name != "modern_metric" {
			return fmt.Errorf("expected stream name 'modern_metric', got '%s'", stream.Name)
		}
		if stream.Description != "remapped metric description" {
			return fmt.Errorf("expected stream description 'remapped metric description', got '%s'", stream.Description)
		}
		if stream.Aggregation != dropAgg {
			return fmt.Errorf("expected stream aggregation AggregationDrop")
		}
		// Unset fields in mask should retain the instrument default
		if stream.Unit != "ms" {
			return fmt.Errorf("expected stream unit 'ms' preserved from instrument, got '%s'", stream.Unit)
		}
	}

	// 4. metric.NewView with empty criteria matches no instruments
	{
		emptyView := metric.NewView(metric.Instrument{}, metric.Stream{Name: "anything"})
		testInst := metric.Instrument{Name: "any_metric", Kind: metric.InstrumentKindCounter}
		_, matched := emptyView(testInst)
		if matched {
			return fmt.Errorf("expected empty criteria view to match no instruments")
		}
	}

	// 5. MeterProvider configured with NewView transforms instrument stream and filters attributes upon collection
	{
		view := sample.NewInstrumentView(sample.ViewConfig{
			InstrumentPattern: "raw_requests",
			RenameTo:          "transformed_requests",
			Description:       "Requests after view transformation",
			AllowedAttributes: []string{"http.method"},
		})

		pipeline := sample.NewMetricsPipeline(view)
		defer pipeline.Shutdown(ctx)

		meter := pipeline.Provider.Meter("contract-test")
		counter, err := meter.Int64Counter("raw_requests")
		if err != nil {
			return fmt.Errorf("failed to create counter: %w", err)
		}

		counter.Add(ctx, 10,
			otelmetric.WithAttributes(
				attribute.String("http.method", "GET"),
				attribute.String("internal.secret", "token123"),
			),
		)

		rm, err := pipeline.Collect(ctx)
		if err != nil {
			return fmt.Errorf("failed to collect metrics: %w", err)
		}

		var targetMetric *metricdata.Metrics
		for _, sm := range rm.ScopeMetrics {
			for i := range sm.Metrics {
				if sm.Metrics[i].Name == "transformed_requests" {
					targetMetric = &sm.Metrics[i]
					break
				}
				if sm.Metrics[i].Name == "raw_requests" {
					return fmt.Errorf("found untransformed metric 'raw_requests'; view was not applied")
				}
			}
		}

		if targetMetric == nil {
			return fmt.Errorf("expected transformed metric 'transformed_requests' not found")
		}

		if targetMetric.Description != "Requests after view transformation" {
			return fmt.Errorf("expected description 'Requests after view transformation', got '%s'", targetMetric.Description)
		}

		sum, ok := targetMetric.Data.(metricdata.Sum[int64])
		if !ok {
			return fmt.Errorf("expected metricdata.Sum[int64], got %T", targetMetric.Data)
		}
		if len(sum.DataPoints) == 0 {
			return fmt.Errorf("expected at least one data point")
		}

		dp := sum.DataPoints[0]
		if dp.Value != 10 {
			return fmt.Errorf("expected data point value 10, got %d", dp.Value)
		}

		if !dp.Attributes.HasValue(attribute.Key("http.method")) {
			return fmt.Errorf("expected allowed attribute 'http.method' to be present")
		}
		if dp.Attributes.HasValue(attribute.Key("internal.secret")) {
			return fmt.Errorf("expected filtered attribute 'internal.secret' to be stripped by AttributeFilter")
		}
	}

	return nil
}
view.go
package sample

import (
	"context"
	"fmt"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

// ViewConfig holds configuration for creating metric views.
type ViewConfig struct {
	InstrumentPattern string
	RenameTo          string
	Description       string
	Aggregation       metric.Aggregation
	AllowedAttributes []string
}

// NewInstrumentView constructs a metric.View using metric.NewView based on the provided configuration.
func NewInstrumentView(cfg ViewConfig) metric.View {
	criteria := metric.Instrument{
		Name: cfg.InstrumentPattern,
	}

	stream := metric.Stream{
		Name:        cfg.RenameTo,
		Description: cfg.Description,
		Aggregation: cfg.Aggregation,
	}

	if len(cfg.AllowedAttributes) > 0 {
		keys := make([]attribute.Key, len(cfg.AllowedAttributes))
		for i, k := range cfg.AllowedAttributes {
			keys[i] = attribute.Key(k)
		}
		stream.AttributeFilter = attribute.NewAllowKeysFilter(keys...)
	}

	return metric.NewView(criteria, stream)
}

// MetricsPipeline wraps a MeterProvider and ManualReader configured with views.
type MetricsPipeline struct {
	Reader   *metric.ManualReader
	Provider *metric.MeterProvider
}

// NewMetricsPipeline initializes a MetricsPipeline with a set of views.
func NewMetricsPipeline(views ...metric.View) *MetricsPipeline {
	reader := metric.NewManualReader()

	opts := make([]metric.Option, 0, len(views)+1)
	opts = append(opts, metric.WithReader(reader))
	for _, v := range views {
		opts = append(opts, metric.WithView(v))
	}

	provider := metric.NewMeterProvider(opts...)

	return &MetricsPipeline{
		Reader:   reader,
		Provider: provider,
	}
}

// Collect reads and collects metric data.
func (p *MetricsPipeline) Collect(ctx context.Context) (*metricdata.ResourceMetrics, error) {
	if p == nil || p.Reader == nil {
		return nil, fmt.Errorf("pipeline or reader is nil")
	}
	var rm metricdata.ResourceMetrics
	if err := p.Reader.Collect(ctx, &rm); err != nil {
		return nil, fmt.Errorf("failed to collect metrics: %w", err)
	}
	return &rm, nil
}

// Shutdown flushes and shuts down the MeterProvider.
func (p *MetricsPipeline) Shutdown(ctx context.Context) error {
	if p == nil || p.Provider == nil {
		return nil
	}
	return p.Provider.Shutdown(ctx)
}

オリジンシーダー

匿名