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 debian/x64 · docker에서 contract를 실행해…

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.")
}

오리진 시더

익명