-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
147 lines (134 loc) · 3.56 KB
/
server.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package server
import (
"context"
"net"
"strconv"
"time"
"github.com/ntons/log-go"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
xRequestId = "x-request-id"
xLibraAppId = "x-libra-app-id"
xLibraAppSecret = "x-libra-app-secret"
xLibraRoleId = "x-libra-role-id"
xLibraTrustedAppId = "x-libra-trusted-app-id"
xLibraTrustedUserId = "x-libra-trusted-user-id"
xLibraTrustedRoleId = "x-libra-trusted-role-id"
xLibraTrustedRoleIndex = "x-libra-trusted-role-index"
)
type callKey struct{}
func FromIncomingContext(ctx context.Context) (call *Call, ok bool) {
call, ok = ctx.Value(callKey{}).(*Call)
return
}
type Call struct {
log.Recorder
// these fields can be truested
AppId string
UserId string
RoleId string
RoleIndex int32
}
type Server struct {
// grpc server, implements ServiceRegistrar
s *grpc.Server
grpc.ServiceRegistrar
// life-time control
ctx context.Context
stop context.CancelFunc
// health status
status *health.Server
}
func NewServer(opts ...grpc.ServerOption) *Server {
srv := &Server{status: health.NewServer()}
srv.ctx, srv.stop = context.WithCancel(context.Background())
grpcsrv := grpc.NewServer(append(
opts,
grpc.KeepaliveEnforcementPolicy(
keepalive.EnforcementPolicy{
MinTime: 30 * time.Second,
},
),
grpc.ChainUnaryInterceptor(srv.intercept),
)...)
srv.s, srv.ServiceRegistrar = grpcsrv, grpcsrv
return srv
}
func (srv *Server) ListenAndServe(addr string) (err error) {
lis, err := net.Listen("tcp", addr)
if err != nil {
return
}
defer lis.Close()
return srv.Serve(lis)
}
func (srv *Server) Serve(lis net.Listener) (err error) {
grpc_health_v1.RegisterHealthServer(srv, srv.status)
defer srv.status.Shutdown()
go srv.s.Serve(lis)
defer srv.s.GracefulStop()
<-srv.Done()
return
}
func (srv *Server) Stop() { srv.stop() }
func (srv *Server) Done() <-chan struct{} { return srv.ctx.Done() }
func (srv *Server) intercept(
ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp interface{}, err error) {
if info.Server == srv.status {
return handler(ctx, req)
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "metadata required")
}
log.Debugw("call-in", "method", info.FullMethod, "metadata", md)
fromMD := func(key string) string {
if values := md.Get(key); len(values) > 0 {
return values[0]
}
return ""
}
appId := fromMD(xLibraTrustedAppId)
userId := fromMD(xLibraTrustedUserId)
roleId := fromMD(xLibraTrustedRoleId)
if appId == "" || userId == "" || roleId == "" {
return nil, status.Errorf(
codes.PermissionDenied, "require trusted session")
}
roleIndex, err := strconv.ParseInt(fromMD(xLibraTrustedRoleIndex), 10, 32)
if err != nil {
return nil, status.Errorf(
codes.PermissionDenied, "require trusted session")
}
call := &Call{
Recorder: log.With(log.M{
"app": appId,
"user": userId,
"role": roleId,
"request": fromMD(xRequestId),
}),
AppId: appId,
UserId: userId,
RoleId: roleId,
RoleIndex: int32(roleIndex),
}
defer func() {
if r := recover(); r != nil {
call.Errorf("recover from %v", r)
var ok bool
if err, ok = r.(error); !ok {
err = status.Errorf(codes.Aborted, "%s", r)
}
}
}()
resp, err = handler(context.WithValue(ctx, callKey{}, call), req)
return
}