pb: client interceptors on every dialed connection (#12834)

AddClientUnaryInterceptor registers an interceptor that runs around every
unary call on a connection opened by GrpcDial. GrpcDial installs one
fixed interceptor that consults the registered list at call time, so one
added later also applies to connections already open and cached. With
none registered it only calls through.

Claude-Session: https://claude.ai/code/session_011Upvag1tiz2pnSB8mS2qtK
This commit is contained in:
Chris Lu authored and GitHub committed 2026-11-20 13:05:23 -08:00
1 parent 037c27582f
commit 0c705ec9f2
3 files changed
+137

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
package pb
import (
"context"
"sync/atomic"
"google.golang.org/grpc"
)
// clientUnaryInterceptors run around every unary call on a connection opened
// by GrpcDial, in the order they were added.
var clientUnaryInterceptors atomic.Pointer[[]grpc.UnaryClientInterceptor]
// AddClientUnaryInterceptor makes interceptor run around every unary call on
// connections opened by GrpcDial, those already open included.
func AddClientUnaryInterceptor(interceptor grpc.UnaryClientInterceptor) {
for {
current := clientUnaryInterceptors.Load()
var next []grpc.UnaryClientInterceptor
if current != nil {
next = append(next, *current...)
}
next = append(next, interceptor)
if clientUnaryInterceptors.CompareAndSwap(current, &next) {
return
}
}
}
// interceptClientUnary is installed on every connection, so an interceptor
// added later still applies to it. With none added it only calls through.
func interceptClientUnary(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
chain := clientUnaryInterceptors.Load()
if chain == nil {
return invoker(ctx, method, req, reply, cc, opts...)
}
return chainClientUnary(*chain, invoker)(ctx, method, req, reply, cc, opts...)
}
func chainClientUnary(chain []grpc.UnaryClientInterceptor, invoker grpc.UnaryInvoker) grpc.UnaryInvoker {
if len(chain) == 0 {
return invoker
}
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
return chain[0](ctx, method, req, reply, cc, chainClientUnary(chain[1:], invoker), opts...)
}
}
+89
View File
@@ -0,0 +1,89 @@
package pb
import (
"context"
"net"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
)
func healthClient(t *testing.T) grpc_health_v1.HealthClient {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
grpc_health_v1.RegisterHealthServer(server, health.NewServer())
go server.Serve(listener)
t.Cleanup(server.Stop)
conn, err := GrpcDial(context.Background(), listener.Addr().String(), false, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
return grpc_health_v1.NewHealthClient(conn)
}
func check(t *testing.T, client grpc_health_v1.HealthClient) error {
t.Helper()
_, err := client.Check(context.Background(), &grpc_health_v1.HealthCheckRequest{})
return err
}
func TestClientUnaryInterceptors(t *testing.T) {
previous := clientUnaryInterceptors.Load()
t.Cleanup(func() { clientUnaryInterceptors.Store(previous) })
clientUnaryInterceptors.Store(nil)
// Dialed before any interceptor exists.
client := healthClient(t)
if err := check(t, client); err != nil {
t.Fatalf("call without interceptors: %v", err)
}
var seen []string
record := func(name string) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
seen = append(seen, name+" "+method)
err := invoker(ctx, method, req, reply, cc, opts...)
seen = append(seen, name+" done")
return err
}
}
AddClientUnaryInterceptor(record("first"))
AddClientUnaryInterceptor(record("second"))
// The connection opened earlier picks them up, in order.
if err := check(t, client); err != nil {
t.Fatalf("call with interceptors: %v", err)
}
want := []string{
"first /grpc.health.v1.Health/Check",
"second /grpc.health.v1.Health/Check",
"second done",
"first done",
}
if len(seen) != len(want) {
t.Fatalf("seen = %v, want %v", seen, want)
}
for i := range want {
if seen[i] != want[i] {
t.Fatalf("seen = %v, want %v", seen, want)
}
}
// An interceptor may refuse the call without making it.
refusal := context.DeadlineExceeded
AddClientUnaryInterceptor(func(context.Context, string, any, any, *grpc.ClientConn, grpc.UnaryInvoker, ...grpc.CallOption) error {
return refusal
})
if err := check(t, client); err != refusal {
t.Fatalf("refused call returned %v", err)
}
}
+1
View File
@@ -295,6 +295,7 @@ func GrpcDial(ctx context.Context, address string, waitForReady bool, opts ...gr
}
options = append(options,
grpc.WithChainUnaryInterceptor(interceptClientUnary),
grpc.WithDefaultCallOptions(
grpc.MaxCallSendMsgSize(Max_Message_Size),
grpc.MaxCallRecvMsgSize(Max_Message_Size),