mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
* Adding a way to inject a request ID It is very useful to associate a request ID to each incoming request, this change allows to provide a function to do that via Server Option. The change comes with a default function which will generate a new request ID. The request ID is put in the request context along with a common logger which always logs the request-id We add gRPC interceptors to the server so it can get the request ID out of the gRPC metadata and put it in the common logger stored in the context so as all the log lines using the common logger from the context will have the request ID logged
58 lines
1.8 KiB
Go
58 lines
1.8 KiB
Go
// Copyright 2016 Michal Witkowski. All Rights Reserved.
|
|
// See LICENSE for licensing terms.
|
|
|
|
package grpc_validator
|
|
|
|
import (
|
|
"golang.org/x/net/context"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
)
|
|
|
|
type validator interface {
|
|
Validate() error
|
|
}
|
|
|
|
// UnaryServerInterceptor returns a new unary server interceptor that validates incoming messages.
|
|
//
|
|
// Invalid messages will be rejected with `InvalidArgument` before reaching any userspace handlers.
|
|
func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
|
|
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
|
|
if v, ok := req.(validator); ok {
|
|
if err := v.Validate(); err != nil {
|
|
return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
|
|
}
|
|
}
|
|
return handler(ctx, req)
|
|
}
|
|
}
|
|
|
|
// StreamServerInterceptor returns a new streaming server interceptor that validates incoming messages.
|
|
//
|
|
// The stage at which invalid messages will be rejected with `InvalidArgument` varies based on the
|
|
// type of the RPC. For `ServerStream` (1:m) requests, it will happen before reaching any userspace
|
|
// handlers. For `ClientStream` (n:1) or `BidiStream` (n:m) RPCs, the messages will be rejected on
|
|
// calls to `stream.Recv()`.
|
|
func StreamServerInterceptor() grpc.StreamServerInterceptor {
|
|
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
|
wrapper := &recvWrapper{stream}
|
|
return handler(srv, wrapper)
|
|
}
|
|
}
|
|
|
|
type recvWrapper struct {
|
|
grpc.ServerStream
|
|
}
|
|
|
|
func (s *recvWrapper) RecvMsg(m interface{}) error {
|
|
if err := s.ServerStream.RecvMsg(m); err != nil {
|
|
return err
|
|
}
|
|
if v, ok := m.(validator); ok {
|
|
if err := v.Validate(); err != nil {
|
|
return grpc.Errorf(codes.InvalidArgument, err.Error())
|
|
}
|
|
}
|
|
return nil
|
|
}
|