CodeSampleX

샘플

github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Timer

검증된 샘플 — golang github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Timer. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:dc1b31e5b21cf05a04d09c78757e1d7ffd9e4ab58969675b94d9699fd520f650

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-02

케이스

HOW
목표
verify Timer in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
패키지
심벌
  • Timer
생성일
2026-09-02T21:02:55Z

컨트랙트

  1. metrics.NewTimer returns an initialized Timer with zero count
  2. Timer.Update records duration samples and updates Count, Min, Max, and Sum
  3. Timer.Time measures and records function execution duration
  4. Timer.Snapshot creates an immutable copy with matching metrics
  5. Timer.Stop stops background rate computation cleanly

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go
  • timer.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 Timer in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
Demonstrate these symbols/APIs:
  - Timer

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:3ec5bfbcfa872eaa1ed12235cb03e29612d45a60a36e4b9cf06aea540af63f66","contract":["metrics.NewTimer returns an initialized Timer with zero count","Timer.Update records duration samples and updates Count, Min, Max, and Sum","Timer.Time measures and records function execution duration","Timer.Snapshot creates an immutable copy with matching metrics","Timer.Stop stops background rate computation cleanly"],"goal":"verify Timer in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9","kind":"HOW","packages":["pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"],"schemaVersion":1,"symbols":["Timer"]},"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/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"],"schemaVersion":1,"subject":"pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9","symbols":["Timer"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9
go.sum
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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Timer in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"
  ],
  "symbols": [
    "Timer"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/rcrowley/go-metrics"
	"sample"
)

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

func runContractTests() error {
	tracker := sample.NewRequestTracker()
	defer tracker.Stop()

	t := tracker.Timer()
	if t == nil {
		return fmt.Errorf("expected non-nil Timer")
	}

	// Verify metrics.Timer interface compliance
	var _ metrics.Timer = t

	// 1. metrics.NewTimer returns an initialized Timer with zero count
	directTimer := metrics.NewTimer()
	defer directTimer.Stop()
	if directTimer.Count() != 0 {
		return fmt.Errorf("expected directTimer Count to be 0, got %d", directTimer.Count())
	}
	if count := t.Count(); count != 0 {
		return fmt.Errorf("expected initial Count to be 0, got %d", count)
	}
	if min := t.Min(); min != 0 {
		return fmt.Errorf("expected initial Min to be 0, got %d", min)
	}
	if max := t.Max(); max != 0 {
		return fmt.Errorf("expected initial Max to be 0, got %d", max)
	}
	if sum := t.Sum(); sum != 0 {
		return fmt.Errorf("expected initial Sum to be 0, got %d", sum)
	}

	// 2. Timer.Update records duration samples and updates Count, Min, Max, and Sum
	d1 := 50 * time.Millisecond
	d2 := 150 * time.Millisecond
	tracker.RecordDuration(d1)
	tracker.RecordDuration(d2)

	if count := t.Count(); count != 2 {
		return fmt.Errorf("expected Count to be 2 after updates, got %d", count)
	}
	if min := t.Min(); min != d1.Nanoseconds() {
		return fmt.Errorf("expected Min to be %d ns, got %d ns", d1.Nanoseconds(), min)
	}
	if max := t.Max(); max != d2.Nanoseconds() {
		return fmt.Errorf("expected Max to be %d ns, got %d ns", d2.Nanoseconds(), max)
	}
	expectedSum := (d1 + d2).Nanoseconds()
	if sum := t.Sum(); sum != expectedSum {
		return fmt.Errorf("expected Sum to be %d ns, got %d ns", expectedSum, sum)
	}

	// 3. Timer.Time measures and records function execution duration
	workExecuted := false
	tracker.TimeOperation(func() {
		time.Sleep(5 * time.Millisecond)
		workExecuted = true
	})
	if !workExecuted {
		return fmt.Errorf("expected timed function to execute")
	}
	if count := t.Count(); count != 3 {
		return fmt.Errorf("expected Count to be 3 after TimeOperation, got %d", count)
	}
	if sum := t.Sum(); sum <= expectedSum {
		return fmt.Errorf("expected Sum to increase after TimeOperation, got %d", sum)
	}

	// 4. Timer.Snapshot creates an immutable copy with matching metrics
	snap := tracker.GetSnapshot()
	if snap == nil {
		return fmt.Errorf("expected non-nil snapshot")
	}
	if snap.Count() != t.Count() {
		return fmt.Errorf("snapshot Count mismatch: got %d, want %d", snap.Count(), t.Count())
	}
	if snap.Min() != t.Min() {
		return fmt.Errorf("snapshot Min mismatch: got %d, want %d", snap.Min(), t.Min())
	}
	if snap.Max() != t.Max() {
		return fmt.Errorf("snapshot Max mismatch: got %d, want %d", snap.Max(), t.Max())
	}
	if snap.Sum() != t.Sum() {
		return fmt.Errorf("snapshot Sum mismatch: got %d, want %d", snap.Sum(), t.Sum())
	}

	// Verify snapshot immutability
	countBefore := snap.Count()
	tracker.RecordDuration(25 * time.Millisecond)
	if snap.Count() != countBefore {
		return fmt.Errorf("snapshot Count mutated after subsequent timer update")
	}

	panicked := false
	func() {
		defer func() {
			if r := recover(); r != nil {
				panicked = true
			}
		}()
		snap.Update(time.Millisecond)
	}()
	if !panicked {
		return fmt.Errorf("expected calling Update on TimerSnapshot to panic")
	}

	// 5. Timer.Stop stops background rate computation cleanly
	tracker.Stop()

	return nil
}
timer.go
package sample

import (
	"time"

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

// RequestTracker wraps a metrics.Timer to measure operation latencies.
type RequestTracker struct {
	timer metrics.Timer
}

// NewRequestTracker creates and initializes a RequestTracker with a new Timer.
func NewRequestTracker() *RequestTracker {
	return &RequestTracker{
		timer: metrics.NewTimer(),
	}
}

// Timer returns the underlying metrics.Timer.
func (rt *RequestTracker) Timer() metrics.Timer {
	return rt.timer
}

// RecordDuration records a specific execution duration into the Timer.
func (rt *RequestTracker) RecordDuration(d time.Duration) {
	rt.timer.Update(d)
}

// TimeOperation measures the execution duration of the given function.
func (rt *RequestTracker) TimeOperation(work func()) {
	rt.timer.Time(work)
}

// GetSnapshot returns a point-in-time snapshot copy of the Timer.
func (rt *RequestTracker) GetSnapshot() metrics.Timer {
	return rt.timer.Snapshot()
}

// Stop stops the timer and meter background processing.
func (rt *RequestTracker) Stop() {
	rt.timer.Stop()
}

오리진 시더

익명