CodeSampleX

サンプル

google.golang.org/grpc v1.71.0: ChainUnaryInterceptor

検証済みサンプル — golang google.golang.org/grpc v1.71.0: ChainUnaryInterceptor. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:6fd8ec6bf7e3bd03516c9e486782949505c69280e2c945d300633b9df89a1345

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
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-02

ケース

HOW
ゴール
verify google.golang.org/grpc.ChainUnaryInterceptor in pkg:golang/google.golang.org/grpc@v1.71.0
パッケージ
シンボル
  • google.golang.org/grpc.ChainUnaryInterceptor
作成日
2026-09-02T19:52:24Z

コントラクト

  1. grpc.ChainUnaryInterceptor returns a non-nil ServerOption when chaining unary server interceptors.
  2. When configured via grpc.ChainUnaryInterceptor, incoming unary RPC calls execute interceptors in the forward order passed during server creation.
  3. Context values attached to context.Context by an earlier interceptor in ChainUnaryInterceptor are accessible to downstream interceptors and the final service handler.
  4. If an interceptor in ChainUnaryInterceptor returns an error, subsequent interceptors and the service handler are not executed, and that error status is returned to the client.

ファイル

  • PROMPT.md
  • chain.go
  • csx.json
  • go.mod
  • go.sum
  • 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/grpc.ChainUnaryInterceptor in pkg:golang/google.golang.org/grpc@v1.71.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/grpc@v1.71.0
Demonstrate these symbols/APIs:
  - google.golang.org/grpc.ChainUnaryInterceptor

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.
chain.go
package sample

import (
	"google.golang.org/grpc"
)

// ChainServerInterceptors chains multiple unary server interceptors using grpc.ChainUnaryInterceptor.
func ChainServerInterceptors(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption {
	return grpc.ChainUnaryInterceptor(interceptors...)
}
csx.json
{"case":{"caseId":"case:sha256:b249777850d7cacce06c1b9b5f0f80203a010b35440b9427627384ad31199865","contract":["grpc.ChainUnaryInterceptor returns a non-nil ServerOption when chaining unary server interceptors.","When configured via grpc.ChainUnaryInterceptor, incoming unary RPC calls execute interceptors in the forward order passed during server creation.","Context values attached to context.Context by an earlier interceptor in ChainUnaryInterceptor are accessible to downstream interceptors and the final service handler.","If an interceptor in ChainUnaryInterceptor returns an error, subsequent interceptors and the service handler are not executed, and that error status is returned to the client."],"goal":"verify google.golang.org/grpc.ChainUnaryInterceptor in pkg:golang/google.golang.org/grpc@v1.71.0","kind":"HOW","packages":["pkg:golang/google.golang.org/grpc@v1.71.0"],"schemaVersion":1,"symbols":["google.golang.org/grpc.ChainUnaryInterceptor"]},"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/grpc@v1.71.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/grpc@v1.71.0","symbols":["google.golang.org/grpc.ChainUnaryInterceptor"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.25.0

require (
	google.golang.org/grpc v1.71.0
	google.golang.org/protobuf v1.36.5
)

require (
	golang.org/x/net v0.34.0 // indirect
	golang.org/x/sys v0.29.0 // indirect
	golang.org/x/text v0.21.0 // indirect
	google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect
)
go.sum
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/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.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50=
google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg=
google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/grpc.ChainUnaryInterceptor in pkg:golang/google.golang.org/grpc@v1.71.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/grpc@v1.71.0"
  ],
  "symbols": [
    "google.golang.org/grpc.ChainUnaryInterceptor"
  ]
}
test/contract.go
package main

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

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	emptypb "google.golang.org/protobuf/types/known/emptypb"

	"sample"
)

type ctxKey string

const keyReqID ctxKey = "request-id"

func main() {
	// Assertion 1: grpc.ChainUnaryInterceptor returns a non-nil ServerOption when chaining unary server interceptors.
	dummyInterceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
		return handler(ctx, req)
	}
	opt := sample.ChainServerInterceptors(dummyInterceptor)
	if opt == nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: ChainUnaryInterceptor returned nil ServerOption\n")
		os.Exit(1)
	}
	optDirect := grpc.ChainUnaryInterceptor(dummyInterceptor)
	if optDirect == nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: grpc.ChainUnaryInterceptor returned nil ServerOption\n")
		os.Exit(1)
	}

	// Prepare interceptors for RPC tests
	var executionOrder []string
	var handlerCalled bool
	var handlerObservedReqID string

	interceptor1 := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
		executionOrder = append(executionOrder, "interceptor1_start")
		md, _ := metadata.FromIncomingContext(ctx)
		if vals := md.Get("x-reject-at"); len(vals) > 0 && vals[0] == "interceptor1" {
			return nil, status.Error(codes.PermissionDenied, "rejected by interceptor1")
		}
		enrichedCtx := context.WithValue(ctx, keyReqID, "req-xyz-987")
		resp, err := handler(enrichedCtx, req)
		executionOrder = append(executionOrder, "interceptor1_end")
		return resp, err
	}

	interceptor2 := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
		executionOrder = append(executionOrder, "interceptor2_start")
		reqID, ok := ctx.Value(keyReqID).(string)
		if !ok || reqID != "req-xyz-987" {
			return nil, status.Error(codes.Internal, "context value missing in interceptor2")
		}
		md, _ := metadata.FromIncomingContext(ctx)
		if vals := md.Get("x-reject-at"); len(vals) > 0 && vals[0] == "interceptor2" {
			return nil, status.Error(codes.Unauthenticated, "rejected by interceptor2")
		}
		resp, err := handler(ctx, req)
		executionOrder = append(executionOrder, "interceptor2_end")
		return resp, err
	}

	lis := bufconn.Listen(1024 * 1024)
	server := grpc.NewServer(
		sample.ChainServerInterceptors(interceptor1, interceptor2),
	)

	server.RegisterService(&grpc.ServiceDesc{
		ServiceName: "test.EchoService",
		HandlerType: (*any)(nil),
		Methods: []grpc.MethodDesc{
			{
				MethodName: "Echo",
				Handler: func(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
					in := new(emptypb.Empty)
					if err := dec(in); err != nil {
						return nil, err
					}
					if interceptor == nil {
						return in, nil
					}
					info := &grpc.UnaryServerInfo{
						Server:     srv,
						FullMethod: "/test.EchoService/Echo",
					}
					handler := func(ctx context.Context, req any) (any, error) {
						handlerCalled = true
						if v, ok := ctx.Value(keyReqID).(string); ok {
							handlerObservedReqID = v
						}
						executionOrder = append(executionOrder, "handler")
						return req, nil
					}
					return interceptor(ctx, in, info, handler)
				},
			},
		},
		Streams: []grpc.StreamDesc{},
	}, nil)

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

	dialer := func(context.Context, string) (net.Conn, error) {
		return lis.Dial()
	}

	cc, err := grpc.NewClient("passthrough://localhost/bufnet",
		grpc.WithContextDialer(dialer),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create ClientConn: %v\n", err)
		os.Exit(1)
	}
	defer cc.Close()

	// Test Assertion 2 & 3: forward order execution and context propagation
	{
		executionOrder = nil
		handlerCalled = false
		handlerObservedReqID = ""

		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()

		req := &emptypb.Empty{}
		resp := &emptypb.Empty{}
		err := cc.Invoke(ctx, "/test.EchoService/Echo", req, resp)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: Invoke returned error: %v\n", err)
			os.Exit(1)
		}
		if !handlerCalled {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: handler was not called\n")
			os.Exit(1)
		}
		if handlerObservedReqID != "req-xyz-987" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected propagated context value req-xyz-987, got %q\n", handlerObservedReqID)
			os.Exit(1)
		}
		expectedOrder := []string{
			"interceptor1_start",
			"interceptor2_start",
			"handler",
			"interceptor2_end",
			"interceptor1_end",
		}
		if !reflect.DeepEqual(executionOrder, expectedOrder) {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: execution order mismatch: got %v, want %v\n", executionOrder, expectedOrder)
			os.Exit(1)
		}
	}

	// Test Assertion 4: interceptor error aborts subsequent interceptors and handler
	{
		executionOrder = nil
		handlerCalled = false

		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()

		ctx = metadata.AppendToOutgoingContext(ctx, "x-reject-at", "interceptor1")

		req := &emptypb.Empty{}
		resp := &emptypb.Empty{}
		err := cc.Invoke(ctx, "/test.EchoService/Echo", req, resp)
		if err == nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected error from rejected call, got nil\n")
			os.Exit(1)
		}
		st, ok := status.FromError(err)
		if !ok || st.Code() != codes.PermissionDenied {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected codes.PermissionDenied, got %v\n", err)
			os.Exit(1)
		}
		if handlerCalled {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: handler must not be called when interceptor1 rejects\n")
			os.Exit(1)
		}
		expectedOrder := []string{
			"interceptor1_start",
		}
		if !reflect.DeepEqual(executionOrder, expectedOrder) {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: execution order mismatch on rejection: got %v, want %v\n", executionOrder, expectedOrder)
			os.Exit(1)
		}
	}

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

オリジンシーダー

匿名