CodeSampleX

Пример

google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9: errdetails.PreconditionFailure_Violation

Проверенный пример — golang google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9: errdetails.PreconditionFailure_Violation. Контракт…

sha256:7b5a5eaa01069f73f687236f6c512e5a8ed1c2645bffd47c80aaede28b4eab3c

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Кейс

HOW
Цель
verify google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation in pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9
Пакеты
Символы
  • google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation
Создан
2026-08-27T11:45:21Z

Контракт

  1. PreconditionFailure_Violation constructs with Type, Subject, and Description and returns values via getters
  2. PreconditionFailure encapsulates multiple PreconditionFailure_Violation instances in Violations list
  3. PreconditionFailure containing PreconditionFailure_Violation round-trips correctly through protobuf binary serialization
  4. PreconditionFailure containing PreconditionFailure_Violation packs into and unpacks from anypb.Any
  5. status.Status holds PreconditionFailure with PreconditionFailure_Violation in Details field
  6. PreconditionFailure_Violation supports Reset, String formatting, and ProtoReflect message inspection

Файлы

  • 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: verify google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation in pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9
Demonstrate these symbols/APIs:
  - google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation

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:99ef700ba4b85f6ed1b65b0a1ab321203245a4d419110a1c350028d84fc0d823","contract":["PreconditionFailure_Violation constructs with Type, Subject, and Description and returns values via getters","PreconditionFailure encapsulates multiple PreconditionFailure_Violation instances in Violations list","PreconditionFailure containing PreconditionFailure_Violation round-trips correctly through protobuf binary serialization","PreconditionFailure containing PreconditionFailure_Violation packs into and unpacks from anypb.Any","status.Status holds PreconditionFailure with PreconditionFailure_Violation in Details field","PreconditionFailure_Violation supports Reset, String formatting, and ProtoReflect message inspection"],"goal":"verify google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation in pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9","kind":"HOW","packages":["pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9"],"schemaVersion":1,"symbols":["google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation"]},"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/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9","symbols":["google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require (
	google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9
	google.golang.org/protobuf v1.35.1
)
go.sum
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 h1:QCqS/PdaHTSWGvupk2F/ehwHtGc0/GYkT+3GAcR1CCc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
main.go
package main

import (
	"fmt"
	"log"

	"google.golang.org/genproto/googleapis/rpc/code"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
)

func main() {
	// Create PreconditionFailure_Violation instances describing precondition failures
	violation1 := &errdetails.PreconditionFailure_Violation{
		Type:        "TOS",
		Subject:     "terms-of-service/v2",
		Description: "User must accept terms of service version 2 before proceeding",
	}

	violation2 := &errdetails.PreconditionFailure_Violation{
		Type:        "PAYMENT_METHOD",
		Subject:     "billing/account/123",
		Description: "A valid default payment method is required",
	}

	// Encapsulate violations inside PreconditionFailure
	precondFailure := &errdetails.PreconditionFailure{
		Violations: []*errdetails.PreconditionFailure_Violation{violation1, violation2},
	}

	// Pack into protobuf Any
	anyPrecond, err := anypb.New(precondFailure)
	if err != nil {
		log.Fatalf("failed to pack precondition failure: %v", err)
	}

	// Attach to an RPC Status with FAILED_PRECONDITION code
	st := &status.Status{
		Code:    int32(code.Code_FAILED_PRECONDITION),
		Message: "Operation failed due to precondition violations",
		Details: []*anypb.Any{anyPrecond},
	}

	// Serialize Status to bytes
	data, err := proto.Marshal(st)
	if err != nil {
		log.Fatalf("failed to marshal status: %v", err)
	}

	// Deserialize Status
	var decoded status.Status
	if err := proto.Unmarshal(data, &decoded); err != nil {
		log.Fatalf("failed to unmarshal status: %v", err)
	}

	fmt.Printf("Status Code: %d\n", decoded.GetCode())
	fmt.Printf("Status Message: %s\n", decoded.GetMessage())

	// Unpack PreconditionFailure and inspect violations
	for _, detail := range decoded.GetDetails() {
		var pf errdetails.PreconditionFailure
		if err := anypb.UnmarshalTo(detail, &pf, proto.UnmarshalOptions{}); err == nil {
			fmt.Printf("Precondition Violations Count: %d\n", len(pf.GetViolations()))
			for i, v := range pf.GetViolations() {
				fmt.Printf("  [%d] Type=%s, Subject=%s, Description=%s\n", i, v.GetType(), v.GetSubject(), v.GetDescription())
			}
		}
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation in pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/genproto/googleapis/rpc@v0.0.0-20241007155032-5fefd90f89a9"
  ],
  "symbols": [
    "google.golang.org/genproto/googleapis/rpc/errdetails.PreconditionFailure_Violation"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	"google.golang.org/genproto/googleapis/rpc/code"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
)

func assert(condition bool, message string) {
	if !condition {
		fmt.Fprintf(os.Stderr, "Assertion failed: %s\n", message)
		os.Exit(1)
	}
}

func main() {
	// 1. PreconditionFailure_Violation constructs with Type, Subject, and Description and returns values via getters
	v1 := &errdetails.PreconditionFailure_Violation{
		Type:        "TOS",
		Subject:     "terms-of-service/v2",
		Description: "Terms of service must be accepted",
	}
	assert(v1.GetType() == "TOS", "GetType() should return 'TOS'")
	assert(v1.GetSubject() == "terms-of-service/v2", "GetSubject() should return 'terms-of-service/v2'")
	assert(v1.GetDescription() == "Terms of service must be accepted", "GetDescription() should return description")

	var nilViolation *errdetails.PreconditionFailure_Violation
	assert(nilViolation.GetType() == "", "nil PreconditionFailure_Violation.GetType() should return empty string")
	assert(nilViolation.GetSubject() == "", "nil PreconditionFailure_Violation.GetSubject() should return empty string")
	assert(nilViolation.GetDescription() == "", "nil PreconditionFailure_Violation.GetDescription() should return empty string")

	// 2. PreconditionFailure encapsulates multiple PreconditionFailure_Violation instances in Violations list
	v2 := &errdetails.PreconditionFailure_Violation{
		Type:        "LOCK_HELD",
		Subject:     "resource/db-1",
		Description: "Exclusive lock held by another session",
	}
	pf := &errdetails.PreconditionFailure{
		Violations: []*errdetails.PreconditionFailure_Violation{v1, v2},
	}
	assert(len(pf.GetViolations()) == 2, "Violations count should be 2")
	assert(pf.GetViolations()[0].GetType() == "TOS", "first violation type should match")
	assert(pf.GetViolations()[1].GetType() == "LOCK_HELD", "second violation type should match")
	assert(pf.GetViolations()[1].GetSubject() == "resource/db-1", "second violation subject should match")

	// 3. PreconditionFailure containing PreconditionFailure_Violation round-trips correctly through protobuf binary serialization
	data, err := proto.Marshal(pf)
	assert(err == nil, "proto.Marshal(pf) should succeed")
	assert(len(data) > 0, "marshaled bytes should not be empty")

	var unmarshaledPf errdetails.PreconditionFailure
	err = proto.Unmarshal(data, &unmarshaledPf)
	assert(err == nil, "proto.Unmarshal should succeed")
	assert(len(unmarshaledPf.GetViolations()) == 2, "unmarshaled violations count must match")
	assert(unmarshaledPf.GetViolations()[0].GetType() == "TOS", "unmarshaled v0 type must match")
	assert(unmarshaledPf.GetViolations()[0].GetSubject() == "terms-of-service/v2", "unmarshaled v0 subject must match")
	assert(unmarshaledPf.GetViolations()[0].GetDescription() == "Terms of service must be accepted", "unmarshaled v0 description must match")
	assert(unmarshaledPf.GetViolations()[1].GetType() == "LOCK_HELD", "unmarshaled v1 type must match")
	assert(unmarshaledPf.GetViolations()[1].GetSubject() == "resource/db-1", "unmarshaled v1 subject must match")
	assert(unmarshaledPf.GetViolations()[1].GetDescription() == "Exclusive lock held by another session", "unmarshaled v1 description must match")

	// 4. PreconditionFailure containing PreconditionFailure_Violation packs into and unpacks from anypb.Any
	anyPf, err := anypb.New(pf)
	assert(err == nil, "anypb.New(pf) should succeed")
	assert(anyPf != nil, "anyPf should not be nil")

	var unpackedPf errdetails.PreconditionFailure
	err = anypb.UnmarshalTo(anyPf, &unpackedPf, proto.UnmarshalOptions{})
	assert(err == nil, "anypb.UnmarshalTo should succeed")
	assert(len(unpackedPf.GetViolations()) == 2, "unpacked violations count must match")
	assert(unpackedPf.GetViolations()[0].GetType() == "TOS", "unpacked v0 type must match")
	assert(unpackedPf.GetViolations()[1].GetSubject() == "resource/db-1", "unpacked v1 subject must match")

	// 5. status.Status holds PreconditionFailure with PreconditionFailure_Violation in Details field
	st := &status.Status{
		Code:    int32(code.Code_FAILED_PRECONDITION),
		Message: "Preconditions not satisfied",
		Details: []*anypb.Any{anyPf},
	}
	assert(st.GetCode() == int32(code.Code_FAILED_PRECONDITION), "status code should match FAILED_PRECONDITION")
	assert(len(st.GetDetails()) == 1, "status details count should be 1")

	stData, err := proto.Marshal(st)
	assert(err == nil, "proto.Marshal(st) should succeed")

	var unmarshaledSt status.Status
	err = proto.Unmarshal(stData, &unmarshaledSt)
	assert(err == nil, "proto.Unmarshal(stData) should succeed")
	assert(len(unmarshaledSt.GetDetails()) == 1, "unmarshaled status should contain 1 detail")

	var extractedPf errdetails.PreconditionFailure
	err = anypb.UnmarshalTo(unmarshaledSt.GetDetails()[0], &extractedPf, proto.UnmarshalOptions{})
	assert(err == nil, "extracting PreconditionFailure from status detail should succeed")
	assert(len(extractedPf.GetViolations()) == 2, "extracted violations count must match")
	assert(extractedPf.GetViolations()[0].GetType() == "TOS", "extracted v0 type must match")
	assert(extractedPf.GetViolations()[1].GetDescription() == "Exclusive lock held by another session", "extracted v1 description must match")

	// 6. PreconditionFailure_Violation supports Reset, String formatting, and ProtoReflect message inspection
	vTest := &errdetails.PreconditionFailure_Violation{
		Type:        "AUTH",
		Subject:     "user/admin",
		Description: "Admin role required",
	}
	vStr := vTest.String()
	assert(strings.Contains(vStr, "AUTH"), "String() output must contain violation type")
	assert(strings.Contains(vStr, "user/admin"), "String() output must contain violation subject")

	refl := vTest.ProtoReflect()
	assert(refl.IsValid(), "ProtoReflect() should return a valid reflect message")
	assert(refl.Descriptor().FullName() == "google.rpc.PreconditionFailure.Violation", "descriptor full name should match")

	vTest.Reset()
	assert(vTest.GetType() == "", "Reset() should clear Type field")
	assert(vTest.GetSubject() == "", "Reset() should clear Subject field")
	assert(vTest.GetDescription() == "", "Reset() should clear Description field")

	fmt.Println("All contract assertions passed successfully.")
}

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

аноним