CodeSampleX

Пример

github.com/jackc/puddle/v2 v2.2.2: create and manage a generic resource pool with puddle.NewPool

Проверенный пример — golang github.com/jackc/puddle/v2 v2.2.2: create and manage a generic resource pool with puddle.NewPool. Контракт выполнен на go 1.26 …

sha256:34a05247790eed03624445ab20a18f0edacaa91da601416d164f4b3821065fec

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-21

Кейс

HOW
Цель
create and manage a generic resource pool with puddle.NewPool
Пакеты
Создан
2026-08-21T00:44:46Z

Контракт

  1. puddle.NewPool initializes a type-parameterized resource pool with constructor and MaxSize config
  2. pool.Acquire creates and leases a resource handle whose Value is accessible and increments AcquiredResources
  3. resource.Release returns the resource to the pool making it available as an idle resource
  4. resource.Destroy removes the resource from the pool invoking the Destructor callback
  5. pool.Close closes the pool and causes subsequent Acquire calls to return ErrClosedPool

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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: create and manage a generic resource pool with puddle.NewPool
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/jackc/puddle/v2@v2.2.2

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:89a576940ce9d0c51cd0d2ad07a73d5388d40b2556bc2baf0aeb02007e184847","contract":["puddle.NewPool initializes a type-parameterized resource pool with constructor and MaxSize config","pool.Acquire creates and leases a resource handle whose Value is accessible and increments AcquiredResources","resource.Release returns the resource to the pool making it available as an idle resource","resource.Destroy removes the resource from the pool invoking the Destructor callback","pool.Close closes the pool and causes subsequent Acquire calls to return ErrClosedPool"],"goal":"create and manage a generic resource pool with puddle.NewPool","kind":"HOW","packages":["pkg:golang/github.com/jackc/puddle/v2@v2.2.2"],"schemaVersion":1},"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/jackc/puddle/v2@v2.2.2"],"schemaVersion":1,"subject":"pkg:golang/github.com/jackc/puddle/v2@v2.2.2","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/jackc/puddle/v2 v2.2.2

require golang.org/x/sync v0.1.0 // indirect
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"context"
	"fmt"
	"sync/atomic"

	"github.com/jackc/puddle/v2"
)

type MockConn struct {
	ID int64
}

func main() {
	ctx := context.Background()
	var nextID int64

	pool, err := puddle.NewPool(&puddle.Config[*MockConn]{
		Constructor: func(ctx context.Context) (*MockConn, error) {
			id := atomic.AddInt64(&nextID, 1)
			return &MockConn{ID: id}, nil
		},
		Destructor: func(c *MockConn) {},
		MaxSize:    5,
	})
	if err != nil {
		panic(err)
	}
	defer pool.Close()

	res, err := pool.Acquire(ctx)
	if err != nil {
		panic(err)
	}
	defer res.Release()

	fmt.Printf("Acquired connection ID: %d\n", res.Value().ID)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create and manage a generic resource pool with puddle.NewPool",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/jackc/puddle/v2@v2.2.2"
  ]
}
test/contract.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"sync/atomic"
	"time"

	"github.com/jackc/puddle/v2"
)

type ResourceItem struct {
	ID int64
}

func main() {
	if err := runContract(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract verification failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All puddle.NewPool contract assertions passed successfully.")
}

func runContract() error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	var createdCount int64
	var destroyedCount int64
	destroyedCh := make(chan int64, 10)

	config := &puddle.Config[*ResourceItem]{
		Constructor: func(ctx context.Context) (*ResourceItem, error) {
			id := atomic.AddInt64(&createdCount, 1)
			return &ResourceItem{ID: id}, nil
		},
		Destructor: func(item *ResourceItem) {
			atomic.AddInt64(&destroyedCount, 1)
			destroyedCh <- item.ID
		},
		MaxSize: 3,
	}

	// Assertion 1: puddle.NewPool initializes a type-parameterized resource pool with constructor and MaxSize config
	pool, err := puddle.NewPool(config)
	if err != nil {
		return fmt.Errorf("failed to create pool: %w", err)
	}
	if pool == nil {
		return fmt.Errorf("expected non-nil pool")
	}
	stat := pool.Stat()
	if stat.MaxResources() != 3 {
		return fmt.Errorf("expected MaxResources 3, got %d", stat.MaxResources())
	}
	if stat.TotalResources() != 0 {
		return fmt.Errorf("expected initial TotalResources 0, got %d", stat.TotalResources())
	}

	// Assertion 2: pool.Acquire creates and leases a resource handle whose Value is accessible and increments AcquiredResources
	res1, err := pool.Acquire(ctx)
	if err != nil {
		return fmt.Errorf("failed to acquire res1: %w", err)
	}
	if res1 == nil || res1.Value() == nil {
		return fmt.Errorf("expected valid resource handle with non-nil value")
	}
	if res1.Value().ID != 1 {
		return fmt.Errorf("expected resource ID 1, got %d", res1.Value().ID)
	}
	stat = pool.Stat()
	if stat.AcquiredResources() != 1 || stat.TotalResources() != 1 || stat.IdleResources() != 0 {
		return fmt.Errorf("unexpected stat after acquire: acquired=%d, total=%d, idle=%d",
			stat.AcquiredResources(), stat.TotalResources(), stat.IdleResources())
	}

	// Assertion 3: resource.Release returns the resource to the pool making it available as an idle resource
	res1.Release()
	stat = pool.Stat()
	if stat.AcquiredResources() != 0 || stat.IdleResources() != 1 {
		return fmt.Errorf("expected 0 acquired and 1 idle after release, got acquired=%d, idle=%d",
			stat.AcquiredResources(), stat.IdleResources())
	}

	// Re-acquiring should reuse the released idle resource rather than constructing a new one
	resReused, err := pool.Acquire(ctx)
	if err != nil {
		return fmt.Errorf("failed to re-acquire resource: %w", err)
	}
	if resReused.Value().ID != 1 {
		return fmt.Errorf("expected reused resource ID 1, got %d", resReused.Value().ID)
	}
	if atomic.LoadInt64(&createdCount) != 1 {
		return fmt.Errorf("expected createdCount 1 after re-acquire, got %d", atomic.LoadInt64(&createdCount))
	}

	// Assertion 4: resource.Destroy removes the resource from the pool invoking the Destructor callback
	resReused.Destroy()

	select {
	case destroyedID := <-destroyedCh:
		if destroyedID != 1 {
			return fmt.Errorf("expected destroyed resource ID 1, got %d", destroyedID)
		}
	case <-time.After(2 * time.Second):
		return fmt.Errorf("timeout waiting for destructor execution")
	}

	pollDeadline := time.Now().Add(2 * time.Second)
	for {
		stat = pool.Stat()
		if stat.TotalResources() == 0 && stat.AcquiredResources() == 0 {
			break
		}
		if time.Now().After(pollDeadline) {
			return fmt.Errorf("expected 0 total and 0 acquired after destroy, got total=%d, acquired=%d",
				stat.TotalResources(), stat.AcquiredResources())
		}
		time.Sleep(10 * time.Millisecond)
	}

	if atomic.LoadInt64(&destroyedCount) != 1 {
		return fmt.Errorf("expected destroyedCount 1, got %d", atomic.LoadInt64(&destroyedCount))
	}

	// Assertion 5: pool.Close closes the pool and causes subsequent Acquire calls to return ErrClosedPool
	pool.Close()
	_, err = pool.Acquire(ctx)
	if !errors.Is(err, puddle.ErrClosedPool) {
		return fmt.Errorf("expected ErrClosedPool on acquire after close, got: %v", err)
	}

	return nil
}

Исходный сидер

аноним