Exemple
google.golang.org/grpc v1.71.0: Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc
Échantillon vérifié pour golang google.golang.org/grpc v1.71.0: Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc. Le contrat s'est…
sha256:67f8983306b7c1690fffded042362f3295d86e5da2339725b56f74146c35a4a4
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
- 3
- 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 | FAIL | compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a… |
2026-09-02 |
| go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 | FAIL | compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a… |
2026-09-03 |
| 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-03 |
Cas
HOW- Objectif
- Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc
- Paquets
- Symboles
-
- google.golang.org/grpc.ChainUnaryInterceptor
- Créé
- 2026-09-02T19:37:58Z
Contrat
- 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.
Fichiers
- NOTES.md
- PROMPT.md
- chain_interceptor_test.go
- csx.json
- go.mod
- go.sum
- interceptor.go
- spec.json
Code source
# Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc
## Search Resolution
A search for existing verified solutions for `google.golang.org/grpc.ChainUnaryInterceptor` on release `v1.71.0` yielded `NO_SAFE_MATCH`.
## Pinned Release
- Package: `google.golang.org/grpc`
- Pinned Version: `v1.71.0`
- Manifest: `go.mod`
- Lockfile: `go.sum`
## Observed Behavior
`google.golang.org/grpc.ChainUnaryInterceptor` returns a `grpc.ServerOption` that chains multiple unary server interceptors for incoming RPCs:
1. **Sequential Execution Order**:
- When configured via `grpc.ChainUnaryInterceptor`, incoming unary RPC calls execute interceptors in the order passed during server creation.
2. **Context Value Propagation**:
- Values attached to `context.Context` by an earlier interceptor in the chain are accessible to subsequent interceptors and the final service handler.
3. **Short-Circuit Error Abort**:
- If an interceptor in the chain aborts execution by returning an error, subsequent interceptors and the service handler are not executed, and the error status is returned directly to the client.
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: Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc
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.
package sample
import (
"context"
"net"
"testing"
"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"
)
type ctxKey string
const (
keyReqID ctxKey = "request-id"
)
func TestChainUnaryInterceptor(t *testing.T) {
var executionOrder []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")
}
// Enrich context for downstream interceptors and handler
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")
// Verify context value propagated from interceptor1
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(
grpc.ChainUnaryInterceptor(interceptor1, interceptor2),
)
var handlerObservedReqID string
var handlerCalled bool
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 {
t.Fatalf("failed to create ClientConn: %v", err)
}
defer cc.Close()
t.Run("interceptors execute in configured order and propagate context to handler", func(t *testing.T) {
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 {
t.Fatalf("Invoke failed: %v", err)
}
if !handlerCalled {
t.Fatalf("expected handler to be called")
}
if handlerObservedReqID != "req-xyz-987" {
t.Fatalf("expected context value req-xyz-987, got %q", handlerObservedReqID)
}
expectedOrder := []string{
"interceptor1_start",
"interceptor2_start",
"handler",
"interceptor2_end",
"interceptor1_end",
}
if len(executionOrder) != len(expectedOrder) {
t.Fatalf("execution order mismatch: got %v, want %v", executionOrder, expectedOrder)
}
for i := range expectedOrder {
if executionOrder[i] != expectedOrder[i] {
t.Fatalf("step %d mismatch: got %s, want %s", i, executionOrder[i], expectedOrder[i])
}
}
})
t.Run("aborting in first interceptor halts subsequent interceptors and handler", func(t *testing.T) {
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 {
t.Fatalf("expected error from rejected call, got nil")
}
if st, ok := status.FromError(err); !ok || st.Code() != codes.PermissionDenied {
t.Fatalf("expected codes.PermissionDenied, got %v", err)
}
if handlerCalled {
t.Fatalf("handler must not be called when interceptor1 rejects")
}
expectedOrder := []string{
"interceptor1_start",
}
if len(executionOrder) != len(expectedOrder) {
t.Fatalf("execution order mismatch: got %v, want %v", executionOrder, expectedOrder)
}
})
t.Run("aborting in second interceptor halts handler and unwinds first interceptor", func(t *testing.T) {
executionOrder = nil
handlerCalled = false
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ctx = metadata.AppendToOutgoingContext(ctx, "x-reject-at", "interceptor2")
req := &emptypb.Empty{}
resp := &emptypb.Empty{}
err := cc.Invoke(ctx, "/test.EchoService/Echo", req, resp)
if err == nil {
t.Fatalf("expected error from rejected call, got nil")
}
if st, ok := status.FromError(err); !ok || st.Code() != codes.Unauthenticated {
t.Fatalf("expected codes.Unauthenticated, got %v", err)
}
if handlerCalled {
t.Fatalf("handler must not be called when interceptor2 rejects")
}
expectedOrder := []string{
"interceptor1_start",
"interceptor2_start",
"interceptor1_end",
}
if len(executionOrder) != len(expectedOrder) {
t.Fatalf("execution order mismatch: got %v, want %v", executionOrder, expectedOrder)
}
for i := range expectedOrder {
if executionOrder[i] != expectedOrder[i] {
t.Fatalf("step %d mismatch: got %s, want %s", i, executionOrder[i], expectedOrder[i])
}
}
})
}
{"case":{"caseId":"case:sha256:08a3a660618d85632545470621115e6d5fd2db90e5e5e8dbcfca76a50fa38ec0","contract":["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":"Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc","kind":"HOW","packages":["pkg:golang/google.golang.org/grpc@v1.71.0"],"schemaVersion":1,"symbols":["google.golang.org/grpc.ChainUnaryInterceptor"]},"contractCommand":["go","test","-mod=readonly","-count=1","./..."],"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"}
module example.com/grpc-chain-interceptor
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
)
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=
package sample
import (
"google.golang.org/grpc"
)
// ChainServerInterceptors returns a ServerOption that chains unary server interceptors.
func ChainServerInterceptors(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption {
return grpc.ChainUnaryInterceptor(interceptors...)
}
{
"schemaVersion": 1,
"goal": "Chain multiple unary server interceptors with ChainUnaryInterceptor in grpc",
"kind": "HOW",
"packages": [
"pkg:golang/google.golang.org/grpc@v1.71.0"
],
"symbols": [
"google.golang.org/grpc.ChainUnaryInterceptor"
]
}
Seeder d'origine
anonyme