CodeSampleX

샘플

google.golang.org/grpc v1.19.0

검증된 샘플 — golang google.golang.org/grpc v1.19.0. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: status.New and status.FromError preserve gRPC…

sha256:2bd18394388024c90f95f1c68c970f8162598363e1012e0f56f83f1055b7a918

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-19

케이스

HOW
목표
verify pkg:golang/google.golang.org/grpc@v1.19.0
패키지
환경
go 1.26.6
생성일
2026-09-19T19:43:33Z

컨트랙트

  1. status.New and status.FromError preserve gRPC status code and description
  2. grpc.DialContext connects to an in-memory listener with insecure credentials and executes configured UnaryClientInterceptor
  3. grpc.Invoke performs unary RPC dispatch and populates response header and trailer metadata passed via grpc.Header and grpc.Trailer CallOptions
  4. grpc.Invoke immediately returns a status error with code Canceled when invoked with an already canceled context
  5. grpc.Invoke returns ErrClientConnClosing when invoked on a closed ClientConn
  6. metadata.Pairs correctly stores and retrieves multiple key-value metadata pairs

파일

  • 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 pkg:golang/google.golang.org/grpc@v1.19.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/grpc@v1.19.0
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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:09c1b2e17495381298e00e0d156f8d26d09edfc1008e3e62e2836f495e20dcd1","contract":["status.New and status.FromError preserve gRPC status code and description","grpc.DialContext connects to an in-memory listener with insecure credentials and executes configured UnaryClientInterceptor","grpc.Invoke performs unary RPC dispatch and populates response header and trailer metadata passed via grpc.Header and grpc.Trailer CallOptions","grpc.Invoke immediately returns a status error with code Canceled when invoked with an already canceled context","grpc.Invoke returns ErrClientConnClosing when invoked on a closed ClientConn","metadata.Pairs correctly stores and retrieves multiple key-value metadata pairs"],"goal":"verify pkg:golang/google.golang.org/grpc@v1.19.0","kind":"HOW","packages":["pkg:golang/google.golang.org/grpc@v1.19.0"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/grpc@v1.19.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/grpc@v1.19.0","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require google.golang.org/grpc v1.19.0

require (
	github.com/golang/protobuf v1.2.0 // indirect
	golang.org/x/net v0.0.0-20180826012351-8a410e7b638d // indirect
	golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 // indirect
	golang.org/x/text v0.3.0 // indirect
	google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 // indirect
)
go.sum
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
main.go
package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)

type rawCodec struct{}

func (rawCodec) Marshal(v interface{}) ([]byte, error) {
	if s, ok := v.(*string); ok {
		return []byte(*s), nil
	}
	return nil, fmt.Errorf("unsupported type %T", v)
}

func (rawCodec) Unmarshal(data []byte, v interface{}) error {
	if s, ok := v.(*string); ok {
		*s = string(data)
		return nil
	}
	return fmt.Errorf("unsupported type %T", v)
}

func (rawCodec) String() string { return "raw" }

func main() {
	lis := bufconn.Listen(1024 * 1024)
	defer lis.Close()

	srv := grpc.NewServer(grpc.CustomCodec(rawCodec{}))
	srv.RegisterService(&grpc.ServiceDesc{
		ServiceName: "example.EchoService",
		HandlerType: (*interface{})(nil),
		Methods: []grpc.MethodDesc{
			{
				MethodName: "Echo",
				Handler: func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
					var in string
					if err := dec(&in); err != nil {
						return nil, err
					}
					_ = grpc.SendHeader(ctx, metadata.Pairs("x-server-meta", "processed"))
					resp := "echo: " + in
					return &resp, nil
				},
			},
		},
		Streams: []grpc.StreamDesc{},
	}, &struct{}{})

	go func() {
		_ = srv.Serve(lis)
	}()
	defer srv.Stop()

	cc, err := grpc.DialContext(
		context.Background(),
		"bufnet",
		grpc.WithInsecure(),
		grpc.WithCodec(rawCodec{}),
		grpc.WithDialer(func(string, time.Duration) (net.Conn, error) {
			return lis.Dial()
		}),
	)
	if err != nil {
		panic(err)
	}
	defer cc.Close()

	req := "hello gRPC"
	var resp string
	var headerMD metadata.MD

	if err := grpc.Invoke(context.Background(), "/example.EchoService/Echo", &req, &resp, cc, grpc.Header(&headerMD)); err != nil {
		panic(err)
	}

	fmt.Printf("Received response: %s\n", resp)
	fmt.Printf("Received metadata: %v\n", headerMD.Get("x-server-meta"))

	st := status.New(codes.OK, "success")
	fmt.Printf("Status: code=%v msg=%s\n", st.Code(), st.Message())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/google.golang.org/grpc@v1.19.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/grpc@v1.19.0"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"net"
	"os"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)

type rawCodec struct{}

func (rawCodec) Marshal(v interface{}) ([]byte, error) {
	if s, ok := v.(*string); ok {
		return []byte(*s), nil
	}
	return nil, fmt.Errorf("unsupported type %T", v)
}

func (rawCodec) Unmarshal(data []byte, v interface{}) error {
	if s, ok := v.(*string); ok {
		*s = string(data)
		return nil
	}
	return fmt.Errorf("unsupported type %T", v)
}

func (rawCodec) String() string { return "raw" }

func main() {
	// Assertion 1: status.New and status.FromError preserve gRPC status code and description
	st := status.New(codes.InvalidArgument, "invalid argument provided")
	if st.Code() != codes.InvalidArgument {
		fmt.Fprintf(os.Stderr, "expected code InvalidArgument, got %v\n", st.Code())
		os.Exit(1)
	}
	if st.Message() != "invalid argument provided" {
		fmt.Fprintf(os.Stderr, "expected message 'invalid argument provided', got %q\n", st.Message())
		os.Exit(1)
	}

	err := st.Err()
	parsedSt, ok := status.FromError(err)
	if !ok || parsedSt.Code() != codes.InvalidArgument || parsedSt.Message() != "invalid argument provided" {
		fmt.Fprintf(os.Stderr, "status.FromError failed to extract status: %v\n", parsedSt)
		os.Exit(1)
	}

	// Setup bufconn listener and server
	lis := bufconn.Listen(1024 * 1024)
	defer lis.Close()

	srv := grpc.NewServer(grpc.CustomCodec(rawCodec{}))
	srv.RegisterService(&grpc.ServiceDesc{
		ServiceName: "test.SampleService",
		HandlerType: (*interface{})(nil),
		Methods: []grpc.MethodDesc{
			{
				MethodName: "UnaryCall",
				Handler: func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
					var in string
					if err := dec(&in); err != nil {
						return nil, err
					}
					if err := grpc.SendHeader(ctx, metadata.Pairs("x-resp-header", "hdr-"+in)); err != nil {
						return nil, err
					}
					if err := grpc.SetTrailer(ctx, metadata.Pairs("x-resp-trailer", "trl-"+in)); err != nil {
						return nil, err
					}
					resp := "echo:" + in
					return &resp, nil
				},
			},
		},
		Streams: []grpc.StreamDesc{},
	}, &struct{}{})

	go func() {
		_ = srv.Serve(lis)
	}()
	defer srv.Stop()

	// Assertion 2: grpc.DialContext connects to an in-memory listener with insecure credentials and executes configured UnaryClientInterceptor
	var interceptorCalled bool
	var interceptedMethod string
	interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		interceptorCalled = true
		interceptedMethod = method
		return invoker(ctx, method, req, reply, cc, opts...)
	}

	cc, err := grpc.DialContext(
		context.Background(),
		"bufnet",
		grpc.WithInsecure(),
		grpc.WithCodec(rawCodec{}),
		grpc.WithDialer(func(string, time.Duration) (net.Conn, error) {
			return lis.Dial()
		}),
		grpc.WithUnaryInterceptor(interceptor),
	)
	if err != nil {
		fmt.Fprintf(os.Stderr, "grpc.DialContext failed: %v\n", err)
		os.Exit(1)
	}
	defer cc.Close()

	// Assertion 3: grpc.Invoke performs unary RPC dispatch and populates response header and trailer metadata passed via grpc.Header and grpc.Trailer CallOptions
	req := "ping"
	var resp string
	var headerMD, trailerMD metadata.MD

	err = grpc.Invoke(
		context.Background(),
		"/test.SampleService/UnaryCall",
		&req,
		&resp,
		cc,
		grpc.Header(&headerMD),
		grpc.Trailer(&trailerMD),
	)
	if err != nil {
		fmt.Fprintf(os.Stderr, "grpc.Invoke failed: %v\n", err)
		os.Exit(1)
	}
	if !interceptorCalled || interceptedMethod != "/test.SampleService/UnaryCall" {
		fmt.Fprintf(os.Stderr, "unary interceptor not called as expected: called=%v method=%q\n", interceptorCalled, interceptedMethod)
		os.Exit(1)
	}
	if resp != "echo:ping" {
		fmt.Fprintf(os.Stderr, "expected response 'echo:ping', got %q\n", resp)
		os.Exit(1)
	}
	if vals := headerMD.Get("x-resp-header"); len(vals) == 0 || vals[0] != "hdr-ping" {
		fmt.Fprintf(os.Stderr, "expected header metadata hdr-ping, got %v\n", headerMD)
		os.Exit(1)
	}
	if vals := trailerMD.Get("x-resp-trailer"); len(vals) == 0 || vals[0] != "trl-ping" {
		fmt.Fprintf(os.Stderr, "expected trailer metadata trl-ping, got %v\n", trailerMD)
		os.Exit(1)
	}

	// Assertion 4: grpc.Invoke immediately returns a status error with code Canceled when invoked with an already canceled context
	canceledCtx, cancel := context.WithCancel(context.Background())
	cancel()

	var canceledResp string
	err = grpc.Invoke(
		canceledCtx,
		"/test.SampleService/UnaryCall",
		&req,
		&canceledResp,
		cc,
	)
	if err == nil {
		fmt.Fprintf(os.Stderr, "expected error on canceled context, got nil\n")
		os.Exit(1)
	}
	if s, ok := status.FromError(err); !ok || s.Code() != codes.Canceled {
		fmt.Fprintf(os.Stderr, "expected status code Canceled, got %v\n", err)
		os.Exit(1)
	}

	// Assertion 5: grpc.Invoke returns ErrClientConnClosing when invoked on a closed ClientConn
	ccClosed, err := grpc.DialContext(
		context.Background(),
		"bufnet",
		grpc.WithInsecure(),
		grpc.WithCodec(rawCodec{}),
		grpc.WithDialer(func(string, time.Duration) (net.Conn, error) {
			return lis.Dial()
		}),
	)
	if err != nil {
		fmt.Fprintf(os.Stderr, "grpc.DialContext failed: %v\n", err)
		os.Exit(1)
	}
	if err := ccClosed.Close(); err != nil {
		fmt.Fprintf(os.Stderr, "cc.Close failed: %v\n", err)
		os.Exit(1)
	}

	err = grpc.Invoke(
		context.Background(),
		"/test.SampleService/UnaryCall",
		&req,
		&canceledResp,
		ccClosed,
	)
	if err != grpc.ErrClientConnClosing {
		fmt.Fprintf(os.Stderr, "expected grpc.ErrClientConnClosing on closed conn, got %v\n", err)
		os.Exit(1)
	}

	// Assertion 6: metadata.Pairs correctly stores and retrieves multiple key-value metadata pairs
	md := metadata.Pairs("test-key", "test-val1", "test-key", "test-val2")
	vals := md.Get("test-key")
	if len(vals) != 2 || vals[0] != "test-val1" || vals[1] != "test-val2" {
		fmt.Fprintf(os.Stderr, "metadata.Pairs failed to store multiple values: %v\n", md)
		os.Exit(1)
	}

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

오리진 시더

익명