CodeSampleX

Exemple

golang.org/x/time v0.15.0: rate.Limiter

Échantillon vérifié pour golang golang.org/x/time v0.15.0: rate.Limiter. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.

sha256:1d179cb929b228f5c7db040df324284f7af3bda7e35ec5800551e4b5379f2638

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-01

Cas

HOW
Objectif
verify rate.Limiter in pkg:golang/golang.org/x/time@v0.15.0
Paquets
Symboles
  • rate.Limiter
Créé
2026-09-01T10:41:08Z

Contrat

  1. rate.NewLimiter initializes a token bucket limiter with Limit and burst size, accessible via Limit() and Burst().
  2. rate.Limiter.Allow and AllowN consume available tokens immediately, returning true when tokens are available and false when burst capacity is exhausted.
  3. rate.Limiter.Reserve and ReserveN return a Reservation with OK() and positive Delay when tokens are temporarily unavailable within burst limits, or OK() false with InfDuration delay when requested tokens exceed burst.
  4. rate.Limiter.Wait and WaitN block until tokens are available, returning nil on success, immediate error if requested tokens exceed burst, or context error when context is cancelled.
  5. Dynamic configuration updates via SetLimit and SetBurst take effect immediately, and Tokens() reports available tokens.

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • ratelimit.go
  • spec.json
  • test/contract_test.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 rate.Limiter in pkg:golang/golang.org/x/time@v0.15.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/time@v0.15.0
Demonstrate these symbols/APIs:
  - rate.Limiter

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:222ed3114cf28f718fd92feb8cc51388ae4edfcdf54a132d3900738e8f63e2ae","contract":["rate.NewLimiter initializes a token bucket limiter with Limit and burst size, accessible via Limit() and Burst().","rate.Limiter.Allow and AllowN consume available tokens immediately, returning true when tokens are available and false when burst capacity is exhausted.","rate.Limiter.Reserve and ReserveN return a Reservation with OK() and positive Delay when tokens are temporarily unavailable within burst limits, or OK() false with InfDuration delay when requested tokens exceed burst.","rate.Limiter.Wait and WaitN block until tokens are available, returning nil on success, immediate error if requested tokens exceed burst, or context error when context is cancelled.","Dynamic configuration updates via SetLimit and SetBurst take effect immediately, and Tokens() reports available tokens."],"goal":"verify rate.Limiter in pkg:golang/golang.org/x/time@v0.15.0","kind":"HOW","packages":["pkg:golang/golang.org/x/time@v0.15.0"],"schemaVersion":1,"symbols":["rate.Limiter"]},"contractCommand":["go","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/golang.org/x/time@v0.15.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/time@v0.15.0","symbols":["rate.Limiter"],"verifierAdapter":"golang@1"}
go.mod
module example.com/ratelimit

go 1.25.0

require golang.org/x/time v0.15.0
go.sum
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
ratelimit.go
package ratelimit

import (
	"context"
	"time"

	"golang.org/x/time/rate"
)

// Limiter manages rate limiting operations wrapping rate.Limiter.
type Limiter struct {
	limiter *rate.Limiter
}

// New creates a new Limiter with a rate limit and burst size.
func New(r rate.Limit, b int) *Limiter {
	return &Limiter{
		limiter: rate.NewLimiter(r, b),
	}
}

// Allow reports whether an event may happen now.
func (l *Limiter) Allow() bool {
	return l.limiter.Allow()
}

// AllowN reports whether n events may happen now.
func (l *Limiter) AllowN(now time.Time, n int) bool {
	return l.limiter.AllowN(now, n)
}

// Wait blocks until the limiter permits one event, or ctx is canceled.
func (l *Limiter) Wait(ctx context.Context) error {
	return l.limiter.Wait(ctx)
}

// WaitN blocks until the limiter permits n events, or ctx is canceled.
func (l *Limiter) WaitN(ctx context.Context, n int) error {
	return l.limiter.WaitN(ctx, n)
}

// Reserve returns a Reservation for 1 event.
func (l *Limiter) Reserve() *rate.Reservation {
	return l.limiter.Reserve()
}

// ReserveN returns a Reservation for n events.
func (l *Limiter) ReserveN(now time.Time, n int) *rate.Reservation {
	return l.limiter.ReserveN(now, n)
}

// Limit returns the current maximum rate.
func (l *Limiter) Limit() rate.Limit {
	return l.limiter.Limit()
}

// Burst returns the current maximum burst size.
func (l *Limiter) Burst() int {
	return l.limiter.Burst()
}

// SetLimit sets a new Limit.
func (l *Limiter) SetLimit(newLimit rate.Limit) {
	l.limiter.SetLimit(newLimit)
}

// SetBurst sets a new burst size.
func (l *Limiter) SetBurst(newBurst int) {
	l.limiter.SetBurst(newBurst)
}

// Tokens returns the number of tokens currently in the bucket.
func (l *Limiter) Tokens() float64 {
	return l.limiter.Tokens()
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify rate.Limiter in pkg:golang/golang.org/x/time@v0.15.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/time@v0.15.0"
  ],
  "symbols": [
    "rate.Limiter"
  ]
}
test/contract_test.go
package test

import (
	"context"
	"testing"
	"time"

	"golang.org/x/time/rate"
	"example.com/ratelimit"
)

func TestLimiterInitialization(t *testing.T) {
	// 1. rate.NewLimiter initializes a token bucket limiter with Limit and burst size
	limit := rate.Limit(10)
	burst := 5
	lim := ratelimit.New(limit, burst)

	if got := lim.Limit(); got != limit {
		t.Fatalf("expected Limit() %v, got %v", limit, got)
	}
	if got := lim.Burst(); got != burst {
		t.Fatalf("expected Burst() %d, got %d", burst, got)
	}
}

func TestLimiterAllow(t *testing.T) {
	// 2. rate.Limiter.Allow and AllowN consume available tokens immediately
	burst := 3
	lim := ratelimit.New(rate.Limit(1), burst)

	for i := 0; i < burst; i++ {
		if !lim.Allow() {
			t.Fatalf("expected Allow() call %d to succeed", i+1)
		}
	}

	if lim.Allow() {
		t.Fatal("expected Allow() to fail when burst is exhausted")
	}

	if lim.AllowN(time.Now(), burst+1) {
		t.Fatal("expected AllowN with n > burst to return false")
	}
}

func TestLimiterReserve(t *testing.T) {
	// 3. rate.Limiter.Reserve and ReserveN return Reservation with OK and Delay
	now := time.Now()
	lim := ratelimit.New(rate.Limit(10), 2)

	if !lim.AllowN(now, 2) {
		t.Fatal("expected AllowN to consume initial tokens")
	}

	res := lim.ReserveN(now, 1)
	if !res.OK() {
		t.Fatal("expected ReserveN to be OK within burst capacity")
	}
	if d := res.DelayFrom(now); d <= 0 {
		t.Fatalf("expected positive delay for empty bucket, got %v", d)
	}

	res.CancelAt(now)

	oversized := lim.ReserveN(now, 10)
	if oversized.OK() {
		t.Fatal("expected ReserveN with n > burst to return OK() == false")
	}
	if oversized.Delay() != rate.InfDuration {
		t.Fatalf("expected InfDuration delay for oversized reservation, got %v", oversized.Delay())
	}
}

func TestLimiterWait(t *testing.T) {
	// 4. rate.Limiter.Wait and WaitN block until tokens are available or context is cancelled
	lim := ratelimit.New(rate.Limit(10), 2)
	ctx := context.Background()

	if err := lim.Wait(ctx); err != nil {
		t.Fatalf("expected Wait() to succeed, got %v", err)
	}

	if err := lim.WaitN(ctx, 10); err == nil {
		t.Fatal("expected WaitN with n > burst to fail immediately")
	}

	cancelCtx, cancel := context.WithCancel(ctx)
	cancel()
	if err := lim.Wait(cancelCtx); err == nil {
		t.Fatal("expected Wait() on cancelled context to fail")
	}
}

func TestLimiterReconfiguration(t *testing.T) {
	// 5. Dynamic configuration updates via SetLimit and SetBurst take effect immediately
	lim := ratelimit.New(rate.Limit(5), 2)

	lim.SetLimit(rate.Limit(20))
	if got := lim.Limit(); got != rate.Limit(20) {
		t.Fatalf("expected Limit() 20, got %v", got)
	}

	lim.SetBurst(8)
	if got := lim.Burst(); got != 8 {
		t.Fatalf("expected Burst() 8, got %d", got)
	}

	tokens := lim.Tokens()
	if tokens < 0 || tokens > 8 {
		t.Fatalf("expected tokens between 0 and 8, got %v", tokens)
	}
}

Seeder d'origine

anonyme