CodeSampleX

Пример

github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432: Once

Проверенный пример — golang github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432: Once. Контракт выполнен на go 1.26 · linux…

sha256:473d427af6e0bd7a37afc30d59904afa7c38f7581a5eb94483be9da3fb5a5da5

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-09-04

Кейс

HOW
Цель
verify github.com/cyberdelia/go-metrics-graphite.Once in pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432
Пакеты
Символы
  • github.com/cyberdelia/go-metrics-graphite.Once
Создан
2026-09-04T03:57:22Z

Контракт

  1. graphite.Once returns an error when connecting to an unreachable TCP address
  2. graphite.Once exports Counter metrics with expected prefix and count
  3. graphite.Once exports Gauge and GaugeFloat64 metric values formatted for Graphite
  4. graphite.Once exports Meter metrics including count and rate calculations
  5. graphite.Once exports Histogram statistics and configured percentiles

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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 github.com/cyberdelia/go-metrics-graphite.Once in pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432
Demonstrate these symbols/APIs:
  - github.com/cyberdelia/go-metrics-graphite.Once

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:67b2f5cda3e6b42cfc0aef41478465130804f7274111d8bb75285f7ae6c90404","contract":["graphite.Once returns an error when connecting to an unreachable TCP address","graphite.Once exports Counter metrics with expected prefix and count","graphite.Once exports Gauge and GaugeFloat64 metric values formatted for Graphite","graphite.Once exports Meter metrics including count and rate calculations","graphite.Once exports Histogram statistics and configured percentiles"],"goal":"verify github.com/cyberdelia/go-metrics-graphite.Once in pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432","kind":"HOW","packages":["pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432"],"schemaVersion":1,"symbols":["github.com/cyberdelia/go-metrics-graphite.Once"]},"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/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432"],"schemaVersion":1,"subject":"pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432","symbols":["github.com/cyberdelia/go-metrics-graphite.Once"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require (
	github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432
	github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9
)
go.sum
github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432 h1:M5QgkYacWj0Xs8MhpIK/5uwU02icXpEoSo9sM2aRCps=
github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432/go.mod h1:xwIwAxMvYnVrGJPe2FKx5prTrnAjGOD8zvDOnxnrrkM=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
main.go
package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"sync"
	"time"

	graphite "github.com/cyberdelia/go-metrics-graphite"
	"github.com/rcrowley/go-metrics"
)

func main() {
	// Start an in-memory Graphite TCP receiver on localhost
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatalf("Failed to start mock graphite receiver: %v", err)
	}
	defer ln.Close()

	tcpAddr := ln.Addr().(*net.TCPAddr)
	var wg sync.WaitGroup
	var received []string

	wg.Add(1)
	go func() {
		defer wg.Done()
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		defer conn.Close()

		scanner := bufio.NewScanner(conn)
		for scanner.Scan() {
			received = append(received, scanner.Text())
		}
	}()

	// Register metrics in a go-metrics registry
	reg := metrics.NewRegistry()
	counter := metrics.NewCounter()
	reg.Register("requests.total", counter)
	counter.Inc(100)

	gauge := metrics.NewGauge()
	reg.Register("workers.active", gauge)
	gauge.Update(4)

	// Configure Graphite export and perform a single submission with Once
	cfg := graphite.Config{
		Addr:          tcpAddr,
		Registry:      reg,
		FlushInterval: 10 * time.Second,
		DurationUnit:  time.Millisecond,
		Prefix:        "service",
		Percentiles:   []float64{0.5, 0.95, 0.99},
	}

	if err := graphite.Once(cfg); err != nil {
		log.Fatalf("graphite.Once failed: %v", err)
	}

	wg.Wait()

	fmt.Printf("graphite.Once transmitted %d metric lines:\n", len(received))
	for _, line := range received {
		fmt.Printf("  %s\n", line)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/cyberdelia/go-metrics-graphite.Once in pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/cyberdelia/go-metrics-graphite@v0.0.0-20161219230853-39f87cc3b432"
  ],
  "symbols": [
    "github.com/cyberdelia/go-metrics-graphite.Once"
  ]
}
test/contract.go
package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	"time"

	graphite "github.com/cyberdelia/go-metrics-graphite"
	"github.com/rcrowley/go-metrics"
)

func collectLines(fn func(addr *net.TCPAddr) error) ([]string, error) {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return nil, fmt.Errorf("failed to listen: %w", err)
	}
	defer ln.Close()

	addr := ln.Addr().(*net.TCPAddr)
	done := make(chan struct{})
	var lines []string
	var acceptErr error

	go func() {
		defer close(done)
		conn, err := ln.Accept()
		if err != nil {
			acceptErr = err
			return
		}
		defer conn.Close()

		scanner := bufio.NewScanner(conn)
		for scanner.Scan() {
			lines = append(lines, scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			acceptErr = err
		}
	}()

	if err := fn(addr); err != nil {
		return nil, fmt.Errorf("export failed: %w", err)
	}

	select {
	case <-done:
		if acceptErr != nil {
			return nil, fmt.Errorf("accept error: %w", acceptErr)
		}
		return lines, nil
	case <-time.After(3 * time.Second):
		return nil, fmt.Errorf("timed out waiting for client to finish")
	}
}

func containsPrefix(lines []string, prefix string) bool {
	for _, l := range lines {
		if strings.HasPrefix(l, prefix) {
			return true
		}
	}
	return false
}

func main() {
	// 1. graphite.Once returns an error when connecting to an unreachable TCP address
	{
		ln, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 setup failed: %v\n", err)
			os.Exit(1)
		}
		closedAddr := ln.Addr().(*net.TCPAddr)
		ln.Close()

		cfg := graphite.Config{
			Addr:          closedAddr,
			Registry:      metrics.NewRegistry(),
			FlushInterval: time.Second,
			DurationUnit:  time.Millisecond,
		}
		if err := graphite.Once(cfg); err == nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected error for unreachable address, got nil\n")
			os.Exit(1)
		}
	}

	// 2. graphite.Once exports Counter metrics with expected prefix and count
	{
		reg := metrics.NewRegistry()
		c := metrics.NewCounter()
		reg.Register("requests", c)
		c.Inc(42)

		lines, err := collectLines(func(addr *net.TCPAddr) error {
			return graphite.Once(graphite.Config{
				Addr:          addr,
				Registry:      reg,
				FlushInterval: 10 * time.Second,
				DurationUnit:  time.Millisecond,
				Prefix:        "app",
			})
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed with error: %v\n", err)
			os.Exit(1)
		}
		if !containsPrefix(lines, "app.requests.count 42 ") {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: missing expected counter line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "app.requests.count_ps 4.20 ") {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: missing expected counter rate line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
	}

	// 3. graphite.Once exports Gauge and GaugeFloat64 metric values formatted for Graphite
	{
		reg := metrics.NewRegistry()
		g1 := metrics.NewGauge()
		g1.Update(123)
		reg.Register("workers", g1)

		g2 := metrics.NewGaugeFloat64()
		g2.Update(45.67)
		reg.Register("cpu_ratio", g2)

		lines, err := collectLines(func(addr *net.TCPAddr) error {
			return graphite.Once(graphite.Config{
				Addr:          addr,
				Registry:      reg,
				FlushInterval: 10 * time.Second,
				DurationUnit:  time.Millisecond,
				Prefix:        "metrics",
			})
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed with error: %v\n", err)
			os.Exit(1)
		}
		if !containsPrefix(lines, "metrics.workers.value 123 ") {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: missing gauge integer line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "metrics.cpu_ratio.value 45.670000 ") {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: missing gauge float line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
	}

	// 4. graphite.Once exports Meter metrics including count and rate calculations
	{
		reg := metrics.NewRegistry()
		m := metrics.NewMeter()
		m.Mark(15)
		reg.Register("events", m)

		lines, err := collectLines(func(addr *net.TCPAddr) error {
			return graphite.Once(graphite.Config{
				Addr:          addr,
				Registry:      reg,
				FlushInterval: 10 * time.Second,
				DurationUnit:  time.Millisecond,
				Prefix:        "meter",
			})
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 4 failed with error: %v\n", err)
			os.Exit(1)
		}
		if !containsPrefix(lines, "meter.events.count 15 ") {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: missing meter count line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "meter.events.one-minute ") {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: missing meter one-minute rate line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "meter.events.mean ") {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: missing meter mean rate line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
	}

	// 5. graphite.Once exports Histogram statistics and configured percentiles
	{
		reg := metrics.NewRegistry()
		s := metrics.NewUniformSample(100)
		h := metrics.NewHistogram(s)
		h.Update(10)
		h.Update(20)
		h.Update(30)
		reg.Register("latency", h)

		lines, err := collectLines(func(addr *net.TCPAddr) error {
			return graphite.Once(graphite.Config{
				Addr:          addr,
				Registry:      reg,
				FlushInterval: 10 * time.Second,
				DurationUnit:  time.Millisecond,
				Prefix:        "hist",
				Percentiles:   []float64{0.5, 0.95},
			})
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 5 failed with error: %v\n", err)
			os.Exit(1)
		}
		if !containsPrefix(lines, "hist.latency.count 3 ") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: missing histogram count line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "hist.latency.min 10 ") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: missing histogram min line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "hist.latency.max 30 ") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: missing histogram max line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "hist.latency.50-percentile ") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: missing histogram 50-percentile line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
		if !containsPrefix(lines, "hist.latency.95-percentile ") {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: missing histogram 95-percentile line; received:\n%s\n", strings.Join(lines, "\n"))
			os.Exit(1)
		}
	}

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

Исходный сидер

аноним