CodeSampleX

샘플

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

검증된 샘플 — golang golang.org/x/time v0.11.0: rate.Limiter. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: rate.NewLimiter initializes a token…

sha256:764537fbc86db72ad329aaccb9c4f8039458cb662d20c734a5c25a40dca669fc

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 go linux 24 · ubuntu · glibc 2.39 x64 go go go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-26
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-07

케이스

HOW
목표
verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0
패키지
심벌
  • golang.org/x/time/rate.Limiter
환경
go
생성일
2026-08-26T12:19:45Z

컨트랙트

  1. rate.NewLimiter initializes a token bucket limiter with the specified Limit and burst size, accessible via Limit() and Burst().
  2. rate.Limiter.Allow and AllowN consume available burst tokens immediately, returning true when tokens are available and false when burst capacity is exceeded or exhausted.
  3. rate.Limiter.ReserveN returns a Reservation with OK() true and a positive wait 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, an immediate error if requested tokens exceed burst capacity, or a context cancellation error when the context is cancelled.
  5. Dynamic updates to rate limit and burst size via SetLimit and SetBurst take effect immediately on subsequent token availability queries and acquisitions.

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • limiter_test.go
  • spec.json

소스 아티팩트 내려받기 (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 golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/time@v0.11.0
Demonstrate these symbols/APIs:
  - golang.org/x/time/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:0679903d15004a495d054f9163a762e54a9edafe63123239e3f33af86135abd5","contract":["rate.NewLimiter initializes a token bucket limiter with the specified Limit and burst size, accessible via Limit() and Burst().","rate.Limiter.Allow and AllowN consume available burst tokens immediately, returning true when tokens are available and false when burst capacity is exceeded or exhausted.","rate.Limiter.ReserveN returns a Reservation with OK() true and a positive wait 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, an immediate error if requested tokens exceed burst capacity, or a context cancellation error when the context is cancelled.","Dynamic updates to rate limit and burst size via SetLimit and SetBurst take effect immediately on subsequent token availability queries and acquisitions."],"goal":"verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0","kind":"HOW","packages":["pkg:golang/golang.org/x/time@v0.11.0"],"schemaVersion":1,"symbols":["golang.org/x/time/rate.Limiter"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/time@v0.11.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/time@v0.11.0","symbols":["golang.org/x/time/rate.Limiter"],"verifierAdapter":"golang@1"}
go.mod
module example.com/ratelimiter

go 1.25.0

require golang.org/x/time v0.11.0
go.sum
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
limiter_test.go
package ratelimiter

import (
	"context"
	"testing"
	"time"

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

func TestLimiterInitializationAndProperties(t *testing.T) {
	// 1. Limiter initialization with rate.Limit and burst size
	limit := rate.Limit(10)
	burst := 5
	lim := rate.NewLimiter(limit, burst)

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

	// rate.Every converts duration interval to rate.Limit (e.g. 100ms interval -> 10 ops/sec)
	intervalLimit := rate.Every(100 * time.Millisecond)
	if intervalLimit != rate.Limit(10) {
		t.Fatalf("expected rate.Every(100ms) to equal rate.Limit(10), got %v", intervalLimit)
	}

	// rate.Inf represents infinite rate limiting
	infLim := rate.NewLimiter(rate.Inf, 1)
	if infLim.Limit() != rate.Inf {
		t.Fatalf("expected Limit() to be rate.Inf, got %v", infLim.Limit())
	}
}

func TestLimiterAllowAndAllowN(t *testing.T) {
	// 2. Token consumption via Allow and AllowN
	burst := 3
	lim := rate.NewLimiter(rate.Limit(1), burst)

	// Newly created limiter starts with full burst capacity
	for i := 0; i < burst; i++ {
		if !lim.Allow() {
			t.Fatalf("expected Allow() #%d to succeed with initial burst tokens", i+1)
		}
	}

	// Immediate next Allow() must fail as burst is exhausted
	if lim.Allow() {
		t.Fatalf("expected Allow() to return false when bucket is empty")
	}

	// AllowN with n > burst must return false without affecting state
	if lim.AllowN(time.Now(), burst+1) {
		t.Fatalf("expected AllowN with n > burst to return false")
	}
}

func TestLimiterReserveAndCancel(t *testing.T) {
	// 3. Reservation behavior, delays, and cancellation
	now := time.Now()
	lim := rate.NewLimiter(rate.Limit(10), 2) // 10 tokens/sec -> 100ms per token

	// Exhaust burst
	if !lim.AllowN(now, 2) {
		t.Fatalf("expected AllowN(now, 2) to succeed")
	}

	// Reserve 1 token when bucket is empty
	res := lim.ReserveN(now, 1)
	if !res.OK() {
		t.Fatalf("expected ReserveN to be OK within burst capacity")
	}

	delay := res.DelayFrom(now)
	if delay <= 0 {
		t.Fatalf("expected positive delay for empty bucket, got %v", delay)
	}

	// Canceling the reservation restores the reserved token at the reservation time
	res.CancelAt(now)

	// Attempting to reserve more than burst size fails (OK() == false, Delay == InfDuration)
	oversized := lim.ReserveN(now, 5)
	if oversized.OK() {
		t.Fatalf("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 TestLimiterWaitAndContextCancellation(t *testing.T) {
	// 4. Context-aware blocking with Wait and WaitN
	lim := rate.NewLimiter(rate.Limit(10), 2)

	ctx := context.Background()
	// Consuming within available burst succeeds immediately
	if err := lim.Wait(ctx); err != nil {
		t.Fatalf("expected Wait() to succeed immediately, got %v", err)
	}

	// WaitN with n > burst returns an immediate error without waiting
	if err := lim.WaitN(ctx, 5); err == nil {
		t.Fatalf("expected WaitN with n > burst to fail immediately")
	}

	// Wait with an already-canceled context fails with context error
	cancelCtx, cancel := context.WithCancel(ctx)
	cancel()
	if err := lim.Wait(cancelCtx); err == nil {
		t.Fatalf("expected Wait with canceled context to return error")
	}
}

func TestLimiterDynamicReconfiguration(t *testing.T) {
	// 5. Dynamic mutations of Limit and Burst
	lim := rate.NewLimiter(rate.Limit(5), 2)

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

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

	// Available tokens can be inspected via Tokens()
	tokens := lim.Tokens()
	if tokens < 0 || tokens > 10 {
		t.Fatalf("expected tokens between 0 and 10, got %v", tokens)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/time@v0.11.0"
  ],
  "symbols": [
    "golang.org/x/time/rate.Limiter"
  ]
}

오리진 시더

익명