interceptors.go150 lines, 4.9 KB
| 1 | package grpcx |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "runtime/debug" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 10 | "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" |
| 11 | "google.golang.org/grpc" |
| 12 | "google.golang.org/grpc/codes" |
| 13 | "google.golang.org/grpc/credentials" |
| 14 | "google.golang.org/grpc/keepalive" |
| 15 | "google.golang.org/grpc/metadata" |
| 16 | "google.golang.org/grpc/status" |
| 17 | ) |
| 18 | |
| 19 | // requestIDKey carries request IDs between services: httpx.RequestIDHeader, |
| 20 | // as gRPC metadata, whose keys are always lowercase. |
| 21 | const requestIDKey = "x-request-id" |
| 22 | |
| 23 | // NewServer returns a gRPC server with our interceptors, outermost first: |
| 24 | // request IDs, logging, panic recovery, error mapping, and then the service's |
| 25 | // own, like authentication. creds secure its connections: mTLS, or in tests, |
| 26 | // insecure.NewCredentials(). |
| 27 | func NewServer( |
| 28 | logger *slog.Logger, creds credentials.TransportCredentials, |
| 29 | interceptors ...grpc.UnaryServerInterceptor, |
| 30 | ) *grpc.Server { |
| 31 | chain := append([]grpc.UnaryServerInterceptor{ |
| 32 | RequestID, Log(logger), Recover(logger), Errors, |
| 33 | }, interceptors...) |
| 34 | // The stats handler traces every RPC, and runs before any interceptor, so |
| 35 | // they all see the span. |
| 36 | return grpc.NewServer( |
| 37 | grpc.Creds(creds), |
| 38 | grpc.StatsHandler(otelgrpc.NewServerHandler()), |
| 39 | grpc.ChainUnaryInterceptor(chain...), |
| 40 | // A client keeps its connections for as long as it can, and nothing |
| 41 | // makes it look for new servers until one closes. Closing each after |
| 42 | // thirty seconds or so gets new replicas their share of calls, and |
| 43 | // the grace lets calls in flight finish. |
| 44 | grpc.KeepaliveParams(keepalive.ServerParameters{ |
| 45 | MaxConnectionAge: 30 * time.Second, |
| 46 | MaxConnectionAgeGrace: 10 * time.Second, |
| 47 | }), |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | // RequestID gives every RPC a request ID: the one the caller sent, if it's |
| 52 | // valid, or a new one. Like httpx.RequestID, it puts the ID in the context, |
| 53 | // and on every log line, and sends it back in the response headers. |
| 54 | func RequestID( |
| 55 | ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler, |
| 56 | ) (any, error) { |
| 57 | var sent string |
| 58 | if v := metadata.ValueFromIncomingContext(ctx, requestIDKey); len(v) > 0 { |
| 59 | sent = v[0] |
| 60 | } |
| 61 | ctx, id := httpx.WithRequestID(ctx, sent) |
| 62 | grpc.SetHeader(ctx, metadata.Pairs(requestIDKey, id)) |
| 63 | return handler(ctx, req) |
| 64 | } |
| 65 | |
| 66 | // Log logs one line per RPC when it completes: the method, the status code |
| 67 | // and the duration. Server faults are logged as errors. |
| 68 | func Log(logger *slog.Logger) grpc.UnaryServerInterceptor { |
| 69 | return func( |
| 70 | ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, |
| 71 | ) (any, error) { |
| 72 | start := time.Now() |
| 73 | resp, err := handler(ctx, req) |
| 74 | code := status.Code(err) |
| 75 | level := slog.LevelInfo |
| 76 | if code == codes.Internal || code == codes.Unknown { |
| 77 | level = slog.LevelError |
| 78 | } |
| 79 | logger.LogAttrs(ctx, level, "rpc", |
| 80 | slog.String("method", info.FullMethod), |
| 81 | slog.String("code", code.String()), |
| 82 | slog.Duration("duration", time.Since(start)), |
| 83 | ) |
| 84 | return resp, err |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // Recover turns a panic in a handler into an Internal error, and logs it with |
| 89 | // its stack trace. grpc-go doesn't recover panics: without this, one bad |
| 90 | // request takes the whole server down. |
| 91 | func Recover(logger *slog.Logger) grpc.UnaryServerInterceptor { |
| 92 | return func( |
| 93 | ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, |
| 94 | ) (resp any, err error) { |
| 95 | defer func() { |
| 96 | if v := recover(); v != nil { |
| 97 | logger.ErrorContext(ctx, "panic recovered", |
| 98 | "method", info.FullMethod, |
| 99 | "panic", v, |
| 100 | "stack", string(debug.Stack()), |
| 101 | ) |
| 102 | err = status.Error(codes.Internal, "internal error") |
| 103 | } |
| 104 | }() |
| 105 | return handler(ctx, req) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // Errors turns the errors that handlers return into statuses, with ToStatus. |
| 110 | // Internal errors are logged, and the client only sees a generic message. |
| 111 | func Errors( |
| 112 | ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler, |
| 113 | ) (any, error) { |
| 114 | resp, err := handler(ctx, req) |
| 115 | if err == nil { |
| 116 | return resp, nil |
| 117 | } |
| 118 | s := ToStatus(err) |
| 119 | if s.Code() == codes.Internal { |
| 120 | slog.ErrorContext(ctx, "rpc failed", "err", err) |
| 121 | } |
| 122 | return nil, s.Err() |
| 123 | } |
| 124 | |
| 125 | // Shutdown stops s gracefully: it stops taking new RPCs, and waits for the |
| 126 | // running ones to finish. If ctx ends first, it cancels them. |
| 127 | func Shutdown(ctx context.Context, s *grpc.Server) { |
| 128 | done := make(chan struct{}) |
| 129 | go func() { |
| 130 | s.GracefulStop() |
| 131 | close(done) |
| 132 | }() |
| 133 | select { |
| 134 | case <-done: |
| 135 | case <-ctx.Done(): |
| 136 | s.Stop() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // PropagateRequestID is a client interceptor that sends the request ID in ctx |
| 141 | // along with every RPC, so one ID follows a request across services. |
| 142 | func PropagateRequestID( |
| 143 | ctx context.Context, method string, req, reply any, |
| 144 | cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, |
| 145 | ) error { |
| 146 | if id := httpx.RequestIDFrom(ctx); id != "" { |
| 147 | ctx = metadata.AppendToOutgoingContext(ctx, requestIDKey, id) |
| 148 | } |
| 149 | return invoker(ctx, method, req, reply, cc, opts...) |
| 150 | } |