CodeSampleX

Beispiel

go.opentelemetry.io/otel/metric v1.37.0: Observer

Verifiziertes Beispiel für golang go.opentelemetry.io/otel/metric v1.37.0: Observer. Der Vertrag lief auf go 1.26 · linux debian/x64 · docker und bestand.

sha256:d91dd0ec95c4964ede1cfd9da9fa005b2e246b4999649582773a275878b20d94

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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-16

Fall

HOW
Ziel
verify go.opentelemetry.io/otel/metric.Observer in pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0
Pakete
Symbole
  • go.opentelemetry.io/otel/metric.Observer
Erstellt
2026-09-16T19:37:25Z

Contract

  1. noop.Observer implements metric.Observer and accepts ObserveFloat64 and ObserveInt64
  2. recordingObserver implements metric.Observer and captures ObserveFloat64 values and attributes
  3. recordingObserver captures ObserveInt64 values and attributes
  4. RegisterCallback registers Callback receiving metric.Observer for observable instruments
  5. Callback receives metric.Observer to observe multiple instruments in single pass
  6. Registration Unregister successfully cleans up callback registration

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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

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

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:2e0ddea44e30abe9f3d1eae27e97e354c14ef01c7e77f15e5f975c86758af43e","contract":["noop.Observer implements metric.Observer and accepts ObserveFloat64 and ObserveInt64","recordingObserver implements metric.Observer and captures ObserveFloat64 values and attributes","recordingObserver captures ObserveInt64 values and attributes","RegisterCallback registers Callback receiving metric.Observer for observable instruments","Callback receives metric.Observer to observe multiple instruments in single pass","Registration Unregister successfully cleans up callback registration"],"goal":"verify go.opentelemetry.io/otel/metric.Observer in pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/otel/metric.Observer"]},"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/metric@v1.37.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0","symbols":["go.opentelemetry.io/otel/metric.Observer"],"verifierAdapter":"golang@1"}
go.mod
module example.com/observer-sample

go 1.23.0

require (
	go.opentelemetry.io/otel v1.37.0
	go.opentelemetry.io/otel/metric v1.37.0
)
go.sum
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.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/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.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"context"
	"fmt"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/metric/noop"
)

// recordingObserver implements metric.Observer by embedding noop.Observer
// and recording calls to ObserveFloat64 and ObserveInt64.
type recordingObserver struct {
	noop.Observer
	floatObservations int
	intObservations   int
}

func (r *recordingObserver) ObserveFloat64(obsrv metric.Float64Observable, value float64, opts ...metric.ObserveOption) {
	r.floatObservations++
	cfg := metric.NewObserveConfig(opts)
	attrs := cfg.Attributes()
	fmt.Printf("Observed Float64: value=%f, attrs=%d\n", value, attrs.Len())
}

func (r *recordingObserver) ObserveInt64(obsrv metric.Int64Observable, value int64, opts ...metric.ObserveOption) {
	r.intObservations++
	cfg := metric.NewObserveConfig(opts)
	attrs := cfg.Attributes()
	fmt.Printf("Observed Int64: value=%d, attrs=%d\n", value, attrs.Len())
}

func main() {
	ctx := context.Background()

	// 1. Initialize meter from noop provider
	mp := noop.NewMeterProvider()
	meter := mp.Meter("example.com/observer-sample")

	// 2. Create asynchronous observable instruments
	cpuGauge, err := meter.Float64ObservableGauge(
		"system.cpu.utilization",
		metric.WithDescription("CPU utilization ratio between 0 and 1"),
		metric.WithUnit("1"),
	)
	if err != nil {
		panic(err)
	}

	queueCounter, err := meter.Int64ObservableCounter(
		"queue.messages.processed",
		metric.WithDescription("Total messages processed"),
		metric.WithUnit("{message}"),
	)
	if err != nil {
		panic(err)
	}

	// 3. Define callback matching metric.Callback signature: func(context.Context, metric.Observer) error
	callback := func(ctx context.Context, obs metric.Observer) error {
		obs.ObserveFloat64(
			cpuGauge,
			0.68,
			metric.WithAttributes(attribute.String("host", "worker-01")),
		)
		obs.ObserveInt64(
			queueCounter,
			250,
			metric.WithAttributes(attribute.String("queue", "high-priority")),
		)
		return nil
	}

	// 4. Register callback with meter
	reg, err := meter.RegisterCallback(callback, cpuGauge, queueCounter)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := reg.Unregister(); err != nil {
			panic(err)
		}
	}()

	// 5. Demonstrate custom Observer implementation invoking the callback
	recorder := &recordingObserver{}
	if err := callback(ctx, recorder); err != nil {
		panic(err)
	}

	// 6. Demonstrate noop.Observer directly satisfying metric.Observer
	var noopObs metric.Observer = noop.Observer{}
	noopObs.ObserveFloat64(cpuGauge, 0.5)
	noopObs.ObserveInt64(queueCounter, 10)

	fmt.Println("Observer sample executed successfully.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/otel/metric.Observer in pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/metric@v1.37.0"
  ],
  "symbols": [
    "go.opentelemetry.io/otel/metric.Observer"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"os"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/metric/noop"
)

// testObserver records observations made through metric.Observer.
type testObserver struct {
	noop.Observer
	floatCalls []floatRecord
	intCalls   []intRecord
}

type floatRecord struct {
	instrument metric.Float64Observable
	value      float64
	attrs      attribute.Set
}

type intRecord struct {
	instrument metric.Int64Observable
	value      int64
	attrs      attribute.Set
}

func (o *testObserver) ObserveFloat64(obsrv metric.Float64Observable, value float64, opts ...metric.ObserveOption) {
	cfg := metric.NewObserveConfig(opts)
	o.floatCalls = append(o.floatCalls, floatRecord{
		instrument: obsrv,
		value:      value,
		attrs:      cfg.Attributes(),
	})
}

func (o *testObserver) ObserveInt64(obsrv metric.Int64Observable, value int64, opts ...metric.ObserveOption) {
	cfg := metric.NewObserveConfig(opts)
	o.intCalls = append(o.intCalls, intRecord{
		instrument: obsrv,
		value:      value,
		attrs:      cfg.Attributes(),
	})
}

func main() {
	ctx := context.Background()
	mp := noop.NewMeterProvider()
	meter := mp.Meter("example.com/contract-meter")

	gauge, err := meter.Float64ObservableGauge("contract_cpu")
	if err != nil {
		fmt.Fprintf(os.Stderr, "unexpected error creating Float64ObservableGauge: %v\n", err)
		os.Exit(1)
	}

	counter, err := meter.Int64ObservableCounter("contract_packets")
	if err != nil {
		fmt.Fprintf(os.Stderr, "unexpected error creating Int64ObservableCounter: %v\n", err)
		os.Exit(1)
	}

	// 1. noop.Observer implements metric.Observer and accepts ObserveFloat64 and ObserveInt64
	var noopObs metric.Observer = noop.Observer{}
	noopObs.ObserveFloat64(gauge, 0.42, metric.WithAttributes(attribute.String("env", "test")))
	noopObs.ObserveInt64(counter, 100, metric.WithAttributes(attribute.Int("code", 200)))

	// 2. recordingObserver implements metric.Observer and captures ObserveFloat64 values and attributes
	recorder := &testObserver{}
	var customObs metric.Observer = recorder

	const testFloatVal = 3.14159
	customObs.ObserveFloat64(
		gauge,
		testFloatVal,
		metric.WithAttributes(
			attribute.String("tier", "frontend"),
			attribute.Int("replica", 3),
		),
	)
	if len(recorder.floatCalls) != 1 {
		fmt.Fprintf(os.Stderr, "expected 1 float call, got %d\n", len(recorder.floatCalls))
		os.Exit(1)
	}
	if recorder.floatCalls[0].value != testFloatVal {
		fmt.Fprintf(os.Stderr, "expected float value %f, got %f\n", testFloatVal, recorder.floatCalls[0].value)
		os.Exit(1)
	}
	floatAttrs := recorder.floatCalls[0].attrs
	tierVal, ok := floatAttrs.Value(attribute.Key("tier"))
	if !ok || tierVal.AsString() != "frontend" {
		fmt.Fprintf(os.Stderr, "expected attribute tier=frontend, got ok=%v, val=%v\n", ok, tierVal)
		os.Exit(1)
	}

	// 3. recordingObserver captures ObserveInt64 values and attributes
	const testIntVal = int64(8192)
	customObs.ObserveInt64(
		counter,
		testIntVal,
		metric.WithAttributes(
			attribute.String("direction", "inbound"),
		),
	)
	if len(recorder.intCalls) != 1 {
		fmt.Fprintf(os.Stderr, "expected 1 int call, got %d\n", len(recorder.intCalls))
		os.Exit(1)
	}
	if recorder.intCalls[0].value != testIntVal {
		fmt.Fprintf(os.Stderr, "expected int value %d, got %d\n", testIntVal, recorder.intCalls[0].value)
		os.Exit(1)
	}
	intAttrs := recorder.intCalls[0].attrs
	dirVal, ok := intAttrs.Value(attribute.Key("direction"))
	if !ok || dirVal.AsString() != "inbound" {
		fmt.Fprintf(os.Stderr, "expected attribute direction=inbound, got ok=%v, val=%v\n", ok, dirVal)
		os.Exit(1)
	}

	// 4. RegisterCallback registers Callback receiving metric.Observer for observable instruments
	var cbExecuted bool
	callback := func(c context.Context, obs metric.Observer) error {
		cbExecuted = true
		obs.ObserveFloat64(gauge, 0.99)
		obs.ObserveInt64(counter, 500)
		return nil
	}

	reg, err := meter.RegisterCallback(callback, gauge, counter)
	if err != nil {
		fmt.Fprintf(os.Stderr, "unexpected error registering callback: %v\n", err)
		os.Exit(1)
	}
	if reg == nil {
		fmt.Fprintf(os.Stderr, "expected non-nil Registration\n")
		os.Exit(1)
	}

	// 5. Callback receives metric.Observer to observe multiple instruments in single pass
	cycleRecorder := &testObserver{}
	if err := callback(ctx, cycleRecorder); err != nil {
		fmt.Fprintf(os.Stderr, "callback execution returned error: %v\n", err)
		os.Exit(1)
	}
	if !cbExecuted {
		fmt.Fprintf(os.Stderr, "expected callback to execute\n")
		os.Exit(1)
	}
	if len(cycleRecorder.floatCalls) != 1 || len(cycleRecorder.intCalls) != 1 {
		fmt.Fprintf(os.Stderr, "expected 1 float and 1 int observation from callback, got %d float, %d int\n",
			len(cycleRecorder.floatCalls), len(cycleRecorder.intCalls))
		os.Exit(1)
	}

	// 6. Registration Unregister successfully cleans up callback registration
	if err := reg.Unregister(); err != nil {
		fmt.Fprintf(os.Stderr, "unexpected error during Unregister: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("All Observer contract assertions passed successfully.")
}

Ursprungs-Seeder

anonym