CodeSampleX

Exemplo

github.com/prometheus/client_model v0.5.0: Counter, Gauge, Metric

Amostra verificada para golang github.com/prometheus/client_model v0.5.0: Counter, Gauge, Metric. O contrato rodou em go 1.26 · linux alpine/x64 · docker e…

sha256:9a6822fb6adcf99c47fe3e3042640134db6338e14dfc3f8051ba613888bc9280

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
2
Chaves de assinatura que o compilaram
1
Ambiente declarado go 1.26 linux 24 · ubuntu · glibc 2.39 amd64 go 1.26 go 1.26 go 1

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23
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-07

Caso

HOW
Objetivo
verify pkg:golang/github.com/prometheus/client_model@v0.5.0
Pacotes
Símbolos
  • Counter
  • Gauge
  • Metric
  • MetricFamily
Ambiente
go 1.26.6
Criado
2026-08-23T17:02:31Z

Contrato

  1. NewCounterMetricFamily creates a MetricFamily with MetricType_COUNTER, non-nil Counter, and specified labels and value
  2. NewGaugeMetricFamily creates a MetricFamily with MetricType_GAUGE, non-nil Gauge, and specified labels and value

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • metric.go
  • spec.json
  • test/contract_test.go

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 pkg:golang/github.com/prometheus/client_model@v0.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_model@v0.5.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:c8f812ee717fae42fa3b176e76fd1b38c1b64d7cbf43e7e76bf22e6ee0fad8c2","contract":["NewCounterMetricFamily creates a MetricFamily with MetricType_COUNTER, non-nil Counter, and specified labels and value","NewGaugeMetricFamily creates a MetricFamily with MetricType_GAUGE, non-nil Gauge, and specified labels and value"],"goal":"verify pkg:golang/github.com/prometheus/client_model@v0.5.0","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_model@v0.5.0"],"schemaVersion":1,"symbols":["Counter","Gauge","Metric","MetricFamily"]},"contractCommand":["go","test","./..."],"environment":{"arch":"amd64","distro":"ubuntu","ecosystem":"golang","language":"go","languageVersion":"1.26","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/prometheus/client_model@v0.5.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_model@v0.5.0","symbols":["Counter","Gauge","Metric","MetricFamily"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/prometheus/client_model v0.5.0

require google.golang.org/protobuf v1.31.0 // indirect
go.sum
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
metric.go
package sample

import (
	dto "github.com/prometheus/client_model/go"
)

// StringPtr returns a pointer to the passed string.
func StringPtr(s string) *string {
	return &s
}

// Float64Ptr returns a pointer to the passed float64.
func Float64Ptr(f float64) *float64 {
	return &f
}

// MetricTypePtr returns a pointer to the passed MetricType.
func MetricTypePtr(t dto.MetricType) *dto.MetricType {
	return &t
}

// NewCounterMetricFamily constructs a MetricFamily containing a single Counter metric with labels and value.
func NewCounterMetricFamily(name, help string, labels map[string]string, value float64) *dto.MetricFamily {
	var labelPairs []*dto.LabelPair
	for k, v := range labels {
		labelPairs = append(labelPairs, &dto.LabelPair{
			Name:  StringPtr(k),
			Value: StringPtr(v),
		})
	}

	return &dto.MetricFamily{
		Name: StringPtr(name),
		Help: StringPtr(help),
		Type: MetricTypePtr(dto.MetricType_COUNTER),
		Metric: []*dto.Metric{
			{
				Label: labelPairs,
				Counter: &dto.Counter{
					Value: Float64Ptr(value),
				},
			},
		},
	}
}

// NewGaugeMetricFamily constructs a MetricFamily containing a single Gauge metric with labels and value.
func NewGaugeMetricFamily(name, help string, labels map[string]string, value float64) *dto.MetricFamily {
	var labelPairs []*dto.LabelPair
	for k, v := range labels {
		labelPairs = append(labelPairs, &dto.LabelPair{
			Name:  StringPtr(k),
			Value: StringPtr(v),
		})
	}

	return &dto.MetricFamily{
		Name: StringPtr(name),
		Help: StringPtr(help),
		Type: MetricTypePtr(dto.MetricType_GAUGE),
		Metric: []*dto.Metric{
			{
				Label: labelPairs,
				Gauge: &dto.Gauge{
					Value: Float64Ptr(value),
				},
			},
		},
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/prometheus/client_model@v0.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_model@v0.5.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract_test.go
package test

import (
	"testing"

	dto "github.com/prometheus/client_model/go"
	"sample"
)

func TestCounterMetricFamilyContract(t *testing.T) {
	name := "http_requests_total"
	help := "Total number of HTTP requests made"
	labels := map[string]string{
		"method": "POST",
		"code":   "200",
	}
	value := 150.0

	mf := sample.NewCounterMetricFamily(name, help, labels, value)

	if mf.GetName() != name {
		t.Fatalf("expected metric family name %q, got %q", name, mf.GetName())
	}
	if mf.GetHelp() != help {
		t.Fatalf("expected metric family help %q, got %q", help, mf.GetHelp())
	}
	if mf.GetType() != dto.MetricType_COUNTER {
		t.Fatalf("expected metric family type COUNTER, got %v", mf.GetType())
	}

	metrics := mf.GetMetric()
	if len(metrics) != 1 {
		t.Fatalf("expected 1 metric in family, got %d", len(metrics))
	}

	m := metrics[0]
	if m.GetCounter() == nil {
		t.Fatal("expected Counter metric to be non-nil")
	}
	if m.GetCounter().GetValue() != value {
		t.Fatalf("expected counter value %f, got %f", value, m.GetCounter().GetValue())
	}

	labelPairs := m.GetLabel()
	if len(labelPairs) != len(labels) {
		t.Fatalf("expected %d label pairs, got %d", len(labels), len(labelPairs))
	}

	foundLabels := make(map[string]string)
	for _, lp := range labelPairs {
		foundLabels[lp.GetName()] = lp.GetValue()
	}

	for k, expectedVal := range labels {
		if foundVal, ok := foundLabels[k]; !ok || foundVal != expectedVal {
			t.Fatalf("expected label %s=%s, got %s=%s", k, expectedVal, k, foundVal)
		}
	}
}

func TestGaugeMetricFamilyContract(t *testing.T) {
	name := "memory_usage_bytes"
	help := "Current memory usage in bytes"
	labels := map[string]string{
		"instance": "server-01",
	}
	value := 1073741824.0

	mf := sample.NewGaugeMetricFamily(name, help, labels, value)

	if mf.GetName() != name {
		t.Fatalf("expected metric family name %q, got %q", name, mf.GetName())
	}
	if mf.GetHelp() != help {
		t.Fatalf("expected metric family help %q, got %q", help, mf.GetHelp())
	}
	if mf.GetType() != dto.MetricType_GAUGE {
		t.Fatalf("expected metric family type GAUGE, got %v", mf.GetType())
	}

	metrics := mf.GetMetric()
	if len(metrics) != 1 {
		t.Fatalf("expected 1 metric in family, got %d", len(metrics))
	}

	m := metrics[0]
	if m.GetGauge() == nil {
		t.Fatal("expected Gauge metric to be non-nil")
	}
	if m.GetGauge().GetValue() != value {
		t.Fatalf("expected gauge value %f, got %f", value, m.GetGauge().GetValue())
	}

	labelPairs := m.GetLabel()
	if len(labelPairs) != len(labels) {
		t.Fatalf("expected %d label pairs, got %d", len(labels), len(labelPairs))
	}
	if labelPairs[0].GetName() != "instance" || labelPairs[0].GetValue() != "server-01" {
		t.Fatalf("unexpected label pair: %s=%s", labelPairs[0].GetName(), labelPairs[0].GetValue())
	}
}

Seeder de origem

anônimo