From fc6b2db5b8df9f12387bbe4ce455b14afbaa1a09 Mon Sep 17 00:00:00 2001 From: Rahmat Hidayat Date: Tue, 4 Jun 2024 15:47:36 +0800 Subject: [PATCH] fix: fix grpc call error (#154) * server: put recovery handler at the end of interceptor chains * fix: ensure index accessing safety * chore: replace deprecated ctxlogrus --- internal/server/interceptors.go | 10 ++++++---- internal/server/server.go | 9 +++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/internal/server/interceptors.go b/internal/server/interceptors.go index e93a13570..f3301dc50 100644 --- a/internal/server/interceptors.go +++ b/internal/server/interceptors.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - ctx_logrus "github.com/grpc-ecosystem/go-grpc-middleware/tags/logrus" + "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" "github.com/sirupsen/logrus" "google.golang.org/grpc" "google.golang.org/grpc/metadata" @@ -39,18 +39,20 @@ func enrichRequestMetadata(ctx context.Context, req *http.Request) metadata.MD { func enrichLogrusFields() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - fields := make(logrus.Fields, 0) + fields := make(logrus.Fields) if userEmail, ok := ctx.Value(authenticatedUserEmailContextKey{}).(string); ok { fields[logrusActorKey] = userEmail } if md, ok := metadata.FromIncomingContext(ctx); ok { - fields["http_path"] = md[grpcgatewayHTTPPathKey][0] + if len(md[grpcgatewayHTTPPathKey]) > 0 { + fields["http_path"] = md[grpcgatewayHTTPPathKey][0] + } } if len(fields) > 0 { - ctx_logrus.AddFields(ctx, fields) + ctxlogrus.AddFields(ctx, fields) } return handler(ctx, req) } diff --git a/internal/server/server.go b/internal/server/server.go index 9e63e45ca..eac4ecd48 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -85,16 +85,17 @@ func RunServer(config *Config) error { otelgrpc.StreamServerInterceptor(), )), grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( + grpc_logrus.UnaryServerInterceptor(logrusEntry), + authInterceptor, + enrichLogrusFields(), + otelgrpc.UnaryServerInterceptor(), + grpc_recovery.UnaryServerInterceptor( grpc_recovery.WithRecoveryHandler(func(p interface{}) (err error) { logger.Error(context.Background(), string(debug.Stack())) return status.Errorf(codes.Internal, "Internal error, please check log") }), ), - grpc_logrus.UnaryServerInterceptor(logrusEntry), - authInterceptor, - enrichLogrusFields(), - otelgrpc.UnaryServerInterceptor(), )), )