CodeSampleX

示例

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

已验证示例 — golang golang.org/x/time v0.11.0: rate.Limiter. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: rate.NewLimiter initializes a token bucket…

sha256:764537fbc86db72ad329aaccb9c4f8039458cb662d20c734a5c25a40dca669fc

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

原始种子者

匿名