-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutil.go
59 lines (48 loc) · 2.04 KB
/
util.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
56
57
58
59
package grpc
import (
"context"
"errors"
"regexp"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
healthCheckEndpoint = "/grpc.health.v1.Health/Check"
fullMethodNameRegex = regexp.MustCompile("/([a-zA-Z0-9]+\\.)+[a-zA-Z0-9]+/[a-zA-Z0-9]+")
)
// ParseFullMethodName parses a gRPC full method name into its components
func ParseFullMethodName(fullMethodName string) (packageName, serviceName, methodName string, err error) {
if !fullMethodNameRegex.Match([]byte(fullMethodName)) {
return "", "", "", errors.New("invalid full method name")
}
parts := strings.Split(fullMethodName, "/")
methodName = parts[2]
parts = strings.Split(parts[1], ".")
serviceName = parts[len(parts)-1]
packageName = strings.Join(parts[:len(parts)-1], ".")
return packageName, serviceName, methodName, nil
}
// DisableEverythingUnaryServerInterceptor makes all unary RPCs return UNAVAILABLE.
// This is the nuclear option to stop all client requests and should be used sparingly.
func DisableEverythingUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// Allow health checks to pass so we don't churn servers
if IsHealthCheckEndpoint(info.FullMethod) {
return handler(ctx, req)
}
return nil, status.Error(codes.Unavailable, "temporarily unavailable")
}
}
// DisableEverythingStreamServerInterceptor makes all streaming RPCs return UNAVAILABLE.
// This is the nuclear option to stop all client requests and should be used sparingly.
func DisableEverythingStreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return status.Error(codes.Unavailable, "temporarily unavailable")
}
}
// IsHealthCheckEndpoint returns whether a method is the health check endpoint
func IsHealthCheckEndpoint(methodName string) bool {
return methodName == healthCheckEndpoint
}