Skip to content

Commit

Permalink
fix: fix grpc call error (#154)
Browse files Browse the repository at this point in the history
* server: put recovery handler at the end of interceptor chains

* fix: ensure index accessing safety

* chore: replace deprecated ctxlogrus
  • Loading branch information
rahmatrhd authored Jun 4, 2024
1 parent 8b1dde5 commit fc6b2db
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
10 changes: 6 additions & 4 deletions internal/server/interceptors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}
Expand Down
9 changes: 5 additions & 4 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
)),
)

Expand Down

0 comments on commit fc6b2db

Please sign in to comment.