CodeSampleX

Exemple

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

Échantillon vérifié pour golang github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Timer. Le contrat s'est exécuté sur go 1.26 · linux…

sha256:dc1b31e5b21cf05a04d09c78757e1d7ffd9e4ab58969675b94d9699fd520f650

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify Timer in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
Paquets
Symboles
  • Timer
Créé
2026-09-02T21:02:55Z

Contrat

  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

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go
  • timer.go

Télécharger l’artefact source (tar.gz)

Code source

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()
}

Seeder d'origine

anonyme