CodeSampleX

示例

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

已验证示例 — golang github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Timer. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过.

sha256:dc1b31e5b21cf05a04d09c78757e1d7ffd9e4ab58969675b94d9699fd520f650

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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()
}

原始种子者

匿名