CodeSampleX

Exemple

github.com/googleapis/gax-go/v2 v2.19.0

Échantillon vérifié pour golang github.com/googleapis/gax-go/v2 v2.19.0. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.

sha256:dda87762b9b2d36b78bc8d8133d75d48763ca7ff4e8d5189daa5f9ae65cc3639

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-10-14

Cas

HOW
Objectif
verify pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0
Paquets
Créé
2026-10-14T03:25:55Z

Contrat

  1. gax.XGoogHeader formats key-value pairs into space-separated key/value tokens
  2. gax.InsertMetadataIntoOutgoingContext and gax.BuildHeaders merge context metadata and explicit header pairs into an http.Header
  3. gax.Backoff.Pause returns bounded retry delay durations up to Max
  4. gax.Invoke applies gax.WithPath to CallSettings.Path and retries transient errors matching gax.OnErrorFunc until success or exhaustion

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.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 pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0

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:b8f1971bedb5e8cc4f50038116a6b4e1c19b44d19dbe55d9822d12e74522ac4e","contract":["gax.XGoogHeader formats key-value pairs into space-separated key/value tokens","gax.InsertMetadataIntoOutgoingContext and gax.BuildHeaders merge context metadata and explicit header pairs into an http.Header","gax.Backoff.Pause returns bounded retry delay durations up to Max","gax.Invoke applies gax.WithPath to CallSettings.Path and retries transient errors matching gax.OnErrorFunc until success or exhaustion"],"goal":"verify pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0","kind":"HOW","packages":["pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0"],"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/googleapis/gax-go/v2@v2.19.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.25.0

require github.com/googleapis/gax-go/v2 v2.19.0

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel v1.42.0 // indirect
	go.opentelemetry.io/otel/metric v1.42.0 // indirect
	go.opentelemetry.io/otel/trace v1.42.0 // indirect
	golang.org/x/net v0.52.0 // indirect
	golang.org/x/sys v0.42.0 // indirect
	golang.org/x/text v0.35.0 // indirect
	google.golang.org/api v0.272.0 // indirect
	google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
	google.golang.org/grpc v1.79.2 // indirect
	google.golang.org/protobuf v1.36.11 // indirect
)
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
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/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA=
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA=
google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA=
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE=
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw=
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js=
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 h1:aJmi6DVGGIStN9Mobk/tZOOQUBbj0BPjZjjnOdoZKts=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sample.go
package sample

import (
	"context"
	"errors"
	"net/http"
	"time"

	"github.com/googleapis/gax-go/v2"
)

var ErrTransient = errors.New("transient failure")

// BuildXGoogHeader constructs an x-goog-api-client header string using gax.XGoogHeader.
func BuildXGoogHeader(pairs ...string) string {
	return gax.XGoogHeader(pairs...)
}

// BuildRequestHeaders merges context metadata and explicit header pairs into an http.Header.
func BuildRequestHeaders(ctx context.Context, ctxPairs []string, headerPairs ...string) http.Header {
	if len(ctxPairs) > 0 {
		ctx = gax.InsertMetadataIntoOutgoingContext(ctx, ctxPairs...)
	}
	return gax.BuildHeaders(ctx, headerPairs...)
}

// ComputeBackoffSequence computes n pause durations from a gax.Backoff configuration.
func ComputeBackoffSequence(initial, max time.Duration, multiplier float64, count int) []time.Duration {
	bo := gax.Backoff{
		Initial:    initial,
		Max:        max,
		Multiplier: multiplier,
	}
	out := make([]time.Duration, 0, count)
	for i := 0; i < count; i++ {
		out = append(out, bo.Pause())
	}
	return out
}

// InvokeWithTransientRetry executes an API call using gax.Invoke with gax.WithPath and gax.OnErrorFunc retry options.
func InvokeWithTransientRetry(ctx context.Context, path string, maxAttempts int, fn func(ctx context.Context, settings gax.CallSettings) error) (int, string, error) {
	callCount := 0
	var observedPath string
	opts := []gax.CallOption{
		gax.WithPath(path),
		gax.WithRetry(func() gax.Retryer {
			attempts := 0
			return gax.OnErrorFunc(gax.Backoff{
				Initial:    time.Millisecond,
				Max:        5 * time.Millisecond,
				Multiplier: 1.5,
			}, func(err error) bool {
				attempts++
				return errors.Is(err, ErrTransient) && attempts < maxAttempts
			})
		}),
	}
	err := gax.Invoke(ctx, func(c context.Context, settings gax.CallSettings) error {
		callCount++
		observedPath = settings.Path
		return fn(c, settings)
	}, opts...)
	return callCount, observedPath, err
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/googleapis/gax-go/v2@v2.19.0"
  ]
}
test/contract.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"time"

	"example.com/sample"
	"github.com/googleapis/gax-go/v2"
)

func fail(msg string, args ...any) {
	fmt.Fprintf(os.Stderr, "FAIL: "+msg+"\n", args...)
	os.Exit(1)
}

func main() {
	ctx := context.Background()

	// 1. Verify XGoogHeader, InsertMetadataIntoOutgoingContext, and BuildHeaders formatting
	hdr := sample.BuildXGoogHeader("gl-go", "1.24.0", "gax", "2.19.0")
	if hdr != "gl-go/1.24.0 gax/2.19.0" {
		fail("unexpected XGoogHeader result: %q", hdr)
	}
	httpHdr := sample.BuildRequestHeaders(
		ctx,
		[]string{"x-goog-request-params", "project=demo"},
		"x-goog-api-client", hdr,
	)
	if got := httpHdr["x-goog-api-client"]; len(got) != 1 || got[0] != hdr {
		fail("unexpected x-goog-api-client header slice: %v", got)
	}
	if got := httpHdr["x-goog-request-params"]; len(got) != 1 || got[0] != "project=demo" {
		fail("unexpected x-goog-request-params header slice: %v", got)
	}

	// 2. Verify Backoff.Pause bounds
	pauses := sample.ComputeBackoffSequence(10*time.Millisecond, 25*time.Millisecond, 2.0, 5)
	if len(pauses) != 5 {
		fail("expected 5 backoff pauses, got %d", len(pauses))
	}
	for i, p := range pauses {
		if p < 0 || p > 25*time.Millisecond {
			fail("pause[%d]=%v out of expected [0, 25ms] bounds", i, p)
		}
	}

	// 3. Verify Invoke passes CallSettings.Path via WithPath and retries transient errors via OnErrorFunc
	attempts, path, err := sample.InvokeWithTransientRetry(ctx, "/v1/projects/demo/items", 4, func(c context.Context, settings gax.CallSettings) error {
		return nil
	})
	if err != nil || attempts != 1 || path != "/v1/projects/demo/items" {
		fail("expected immediate success on attempt 1 with path, got attempts=%d path=%q err=%v", attempts, path, err)
	}

	flakyCounter := 0
	attempts, path, err = sample.InvokeWithTransientRetry(ctx, "/v1/projects/demo/flaky", 4, func(c context.Context, settings gax.CallSettings) error {
		flakyCounter++
		if flakyCounter < 3 {
			return sample.ErrTransient
		}
		return nil
	})
	if err != nil || attempts != 3 || path != "/v1/projects/demo/flaky" {
		fail("expected success on 3rd attempt, got attempts=%d path=%q err=%v", attempts, path, err)
	}

	// 4. Verify Invoke stops retrying on non-retryable error or exhausted attempts
	permErr := errors.New("permanent failure")
	attempts, _, err = sample.InvokeWithTransientRetry(ctx, "/v1/projects/demo/perm", 4, func(c context.Context, settings gax.CallSettings) error {
		return permErr
	})
	if !errors.Is(err, permErr) || attempts != 1 {
		fail("expected non-retryable error after 1 attempt, got attempts=%d err=%v", attempts, err)
	}

	attempts, _, err = sample.InvokeWithTransientRetry(ctx, "/v1/projects/demo/exhausted", 3, func(c context.Context, settings gax.CallSettings) error {
		return sample.ErrTransient
	})
	if !errors.Is(err, sample.ErrTransient) || attempts != 3 {
		fail("expected exhausted transient error after 3 attempts, got attempts=%d err=%v", attempts, err)
	}

	fmt.Println("CONTRACT_OK")
}

Seeder d'origine

anonyme