You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/common/mw/rpc_server_interceptor.go

81 lines
2.3 KiB

2 years ago
package mw
2 years ago
import (
2 years ago
"OpenIM/pkg/common/log"
2 years ago
"OpenIM/pkg/common/mw/specialerror"
2 years ago
"OpenIM/pkg/errs"
2 years ago
"context"
2 years ago
"fmt"
2 years ago
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
2 years ago
"math"
2 years ago
"runtime/debug"
2 years ago
)
2 years ago
const OperationID = "operationID"
const OpUserID = "opUserID"
2 years ago
func rpcString(v interface{}) string {
if s, ok := v.(interface{ String() string }); ok {
return s.String()
}
return fmt.Sprintf("%+v", v)
}
2 years ago
func rpcServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
2 years ago
var operationID string
defer func() {
if r := recover(); r != nil {
2 years ago
log.ZError(ctx, "rpc panic", nil, "FullMethod", info.FullMethod, "type:", fmt.Sprintf("%T", r), "panic:", r, string(debug.Stack()))
2 years ago
}
}()
2 years ago
funcName := info.FullMethod
2 years ago
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.New(codes.InvalidArgument, "missing metadata").Err()
}
2 years ago
if opts := md.Get(OperationID); len(opts) != 1 || opts[0] == "" {
2 years ago
return nil, status.New(codes.InvalidArgument, "operationID error").Err()
} else {
operationID = opts[0]
}
var opUserID string
2 years ago
if opts := md.Get(OpUserID); len(opts) == 1 {
2 years ago
opUserID = opts[0]
}
2 years ago
ctx = context.WithValue(ctx, OperationID, operationID)
ctx = context.WithValue(ctx, OpUserID, opUserID)
2 years ago
log.ZInfo(ctx, "rpc req", "funcName", funcName, "req", rpcString(req))
2 years ago
resp, err = handler(ctx, req)
2 years ago
if err == nil {
2 years ago
log.ZInfo(ctx, "rpc resp", "funcName", funcName, "resp", rpcString(resp))
2 years ago
return resp, nil
}
unwrap := errs.Unwrap(err)
codeErr := specialerror.ErrCode(unwrap)
if codeErr == nil {
2 years ago
log.ZError(ctx, "rpc InternalServer error", err, "req", req)
2 years ago
codeErr = errs.ErrInternalServer
}
code := codeErr.Code()
if code <= 0 || code > math.MaxUint32 {
log.ZError(ctx, "rpc UnknownError", err, "rpc UnknownCode:", code)
2 years ago
code = errs.ServerInternalError
}
grpcStatus := status.New(codes.Code(code), codeErr.Msg())
2 years ago
//if unwrap != err {
// stack := fmt.Sprintf("%+v", err)
// if details, err := grpcStatus.WithDetails(wrapperspb.String(stack)); err == nil {
// grpcStatus = details
// }
//}
log.ZWarn(ctx, "rpc resp", unwrap, "funcName", funcName)
2 years ago
return nil, grpcStatus.Err()
2 years ago
}
2 years ago
func GrpcServer() grpc.ServerOption {
return grpc.UnaryInterceptor(rpcServerInterceptor)
}