-
Notifications
You must be signed in to change notification settings - Fork 7
/
interceptor.go
55 lines (41 loc) · 1.64 KB
/
interceptor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package middleware
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"github.com/instill-ai/model-backend/pkg/constant"
)
// RecoveryInterceptor - panic handler
func RecoveryInterceptorOpt() grpc_recovery.Option {
return grpc_recovery.WithRecoveryHandler(func(p interface{}) (err error) {
return status.Errorf(codes.Unknown, "panic triggered: %v", p)
})
}
// CustomInterceptor - append metadatas for unary
func UnaryAppendMetadataInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Internal, "can not extract metadata")
}
md.Append(constant.HeaderOwnerIDKey, constant.DefaultOwnerID)
newCtx := metadata.NewIncomingContext(ctx, md)
h, err := handler(newCtx, req)
return h, err
}
// CustomInterceptor - append metadatas for stream
func StreamAppendMetadataInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
md, ok := metadata.FromIncomingContext(stream.Context())
if !ok {
return status.Error(codes.Internal, "can not extract metadata")
}
md.Append(constant.HeaderOwnerIDKey, constant.DefaultOwnerID)
newCtx := metadata.NewIncomingContext(stream.Context(), md)
wrapped := grpc_middleware.WrapServerStream(stream)
wrapped.WrappedContext = newCtx
err := handler(srv, wrapped)
return err
}