-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
246 lines (234 loc) · 8.1 KB
/
wrapper.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package tuihub
import (
"context"
"fmt"
"sync"
"time"
pb "github.com/tuihub/protos/pkg/librarian/porter/v1"
sephirah "github.com/tuihub/protos/pkg/librarian/sephirah/v1"
librarian "github.com/tuihub/protos/pkg/librarian/v1"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/middleware/logging"
"github.com/go-kratos/kratos/v2/transport/grpc"
)
const (
defaultHeartbeatInterval = time.Second * 10
defaultHeartbeatDowngrade = time.Second * 30
defaultHeartbeatTimeout = time.Second * 60
defaultRefreshToken = time.Hour / 2
)
type serviceWrapper struct {
pb.LibrarianPorterServiceServer
Info *pb.GetPorterInformationResponse
Logger log.Logger
Client sephirah.LibrarianSephirahServiceClient
RequireToken bool
Token *tokenInfo
tokenMu sync.Mutex
lastHeartbeat time.Time
lastRefreshToken time.Time
}
type tokenInfo struct {
enabler int64
AccessToken string
refreshToken string
}
func (s *serviceWrapper) GetPorterInformation(ctx context.Context, req *pb.GetPorterInformationRequest) (
*pb.GetPorterInformationResponse, error) {
return s.Info, nil
}
func (s *serviceWrapper) EnablePorter(ctx context.Context, req *pb.EnablePorterRequest) ( //nolint:gocognit //TODO
*pb.EnablePorterResponse, error) {
needRefreshToken := false
f := func() error {
s.tokenMu.Lock()
defer s.tokenMu.Unlock()
if s.Token != nil { //nolint:nestif //TODO
if s.Token.enabler == req.GetSephirahId() {
if req.GetRefreshToken() != "" {
resp, err := s.Client.RefreshToken(
WithToken(ctx, req.GetRefreshToken()),
new(sephirah.RefreshTokenRequest),
)
if err != nil {
return err
}
s.Token.AccessToken = resp.GetAccessToken()
s.Token.refreshToken = resp.GetRefreshToken()
s.lastRefreshToken = time.Now()
}
if s.RequireToken && (s.lastRefreshToken.Add(defaultRefreshToken).Before(time.Now()) || s.Token.refreshToken == "") {
needRefreshToken = true
}
return nil
} else if s.lastHeartbeat.Add(defaultHeartbeatTimeout).After(time.Now()) {
return fmt.Errorf("porter already enabled by %d", s.Token.enabler)
}
}
s.Token = new(tokenInfo)
s.Token.enabler = req.GetSephirahId()
s.lastHeartbeat = time.Now()
if s.RequireToken {
if req.GetRefreshToken() == "" {
needRefreshToken = true
return nil
}
resp, err := s.Client.RefreshToken(
WithToken(ctx, req.GetRefreshToken()),
new(sephirah.RefreshTokenRequest),
)
if err != nil {
return err
}
s.Token = &tokenInfo{
enabler: req.GetSephirahId(),
AccessToken: resp.GetAccessToken(),
refreshToken: resp.GetRefreshToken(),
}
s.lastRefreshToken = time.Now()
}
return nil
}
if err := f(); err != nil {
return nil, err
}
if resp, err := s.LibrarianPorterServiceServer.EnablePorter(ctx, req); isUnimplementedError(err) {
return &pb.EnablePorterResponse{
StatusMessage: "",
NeedRefreshToken: needRefreshToken,
EnablesSummary: nil,
}, nil
} else {
resp.NeedRefreshToken = needRefreshToken || resp.GetNeedRefreshToken()
return resp, err
}
}
func (s *serviceWrapper) Enabled() bool {
return s.Token != nil
}
func NewServer(c *ServerConfig, service pb.LibrarianPorterServiceServer, logger log.Logger) *grpc.Server {
var middlewares = []middleware.Middleware{
logging.Server(logger),
}
var opts = []grpc.ServerOption{
grpc.Middleware(middlewares...),
}
if c.Network != "" {
opts = append(opts, grpc.Network(c.Network))
}
if c.Addr != "" {
opts = append(opts, grpc.Address(c.Addr))
}
if c.Timeout != nil {
opts = append(opts, grpc.Timeout(*c.Timeout))
} else {
opts = append(opts, grpc.Timeout(time.Minute))
}
srv := grpc.NewServer(opts...)
pb.RegisterLibrarianPorterServiceServer(srv, service)
return srv
}
type serviceServer struct {
*serviceWrapper
}
func NewService(p *serviceWrapper) pb.LibrarianPorterServiceServer {
return &serviceServer{
p,
}
}
func (s *serviceServer) GetPorterInformation(ctx context.Context, req *pb.GetPorterInformationRequest) (
*pb.GetPorterInformationResponse, error) {
return s.serviceWrapper.GetPorterInformation(ctx, req)
}
func (s *serviceServer) EnablePorter(ctx context.Context, req *pb.EnablePorterRequest) (
*pb.EnablePorterResponse, error) {
return s.serviceWrapper.EnablePorter(ctx, req)
}
func (s *serviceServer) PullAccount(ctx context.Context, req *pb.PullAccountRequest) (
*pb.PullAccountResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
if req.GetAccountId() == nil ||
req.GetAccountId().GetPlatform() == "" ||
req.GetAccountId().GetPlatformAccountId() == "" {
return nil, errors.BadRequest("Invalid account id", "")
}
for _, account := range s.serviceWrapper.Info.GetFeatureSummary().GetAccountPlatforms() {
if account.GetId() == req.GetAccountId().GetPlatform() {
return s.serviceWrapper.LibrarianPorterServiceServer.PullAccount(ctx, req)
}
}
return nil, errors.BadRequest("Unsupported account platform", "")
}
func (s *serviceServer) PullAppInfo(ctx context.Context, req *pb.PullAppInfoRequest) (*pb.PullAppInfoResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
if req.GetAppInfoId() == nil ||
req.GetAppInfoId().GetInternal() ||
req.GetAppInfoId().GetSource() == "" ||
req.GetAppInfoId().GetSourceAppId() == "" {
return nil, errors.BadRequest("Invalid app id", "")
}
for _, source := range s.serviceWrapper.Info.GetFeatureSummary().GetAppInfoSources() {
if source.GetId() == req.GetAppInfoId().GetSource() {
return s.serviceWrapper.LibrarianPorterServiceServer.PullAppInfo(ctx, req)
}
}
return nil, errors.BadRequest("Unsupported app source", "")
}
func (s *serviceServer) PullAccountAppInfoRelation(ctx context.Context, req *pb.PullAccountAppInfoRelationRequest) (
*pb.PullAccountAppInfoRelationResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
if req.GetAccountId() == nil ||
req.GetRelationType() == librarian.AccountAppRelationType_ACCOUNT_APP_RELATION_TYPE_UNSPECIFIED ||
req.GetAccountId().GetPlatform() == "" || req.GetAccountId().GetPlatformAccountId() == "" {
return nil, errors.BadRequest("Invalid account id", "")
}
for _, account := range s.serviceWrapper.Info.GetFeatureSummary().GetAccountPlatforms() {
if account.GetId() == req.GetAccountId().GetPlatform() {
return s.serviceWrapper.LibrarianPorterServiceServer.PullAccountAppInfoRelation(ctx, req)
}
}
return nil, errors.BadRequest("Unsupported account", "")
}
func (s *serviceServer) SearchAppInfo(ctx context.Context, req *pb.SearchAppInfoRequest) (*pb.SearchAppInfoResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
if req.GetName() == "" {
return nil, errors.BadRequest("Invalid app name", "")
}
if len(s.serviceWrapper.Info.GetFeatureSummary().GetAppInfoSources()) > 0 {
return s.serviceWrapper.LibrarianPorterServiceServer.SearchAppInfo(ctx, req)
}
return nil, errors.BadRequest("Unsupported app source", "")
}
func (s *serviceServer) PullFeed(ctx context.Context, req *pb.PullFeedRequest) (*pb.PullFeedResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
for _, source := range s.serviceWrapper.Info.GetFeatureSummary().GetFeedSources() {
if source.GetId() == req.GetSource().GetId() {
return s.serviceWrapper.LibrarianPorterServiceServer.PullFeed(ctx, req)
}
}
return nil, errors.BadRequest("Unsupported feed source", "")
}
func (s *serviceServer) PushFeedItems(ctx context.Context, req *pb.PushFeedItemsRequest) (
*pb.PushFeedItemsResponse, error) {
if !s.serviceWrapper.Enabled() {
return nil, errors.Forbidden("Unauthorized caller", "")
}
for _, destination := range s.serviceWrapper.Info.GetFeatureSummary().GetNotifyDestinations() {
if destination.GetId() == req.GetDestination().GetId() {
return s.serviceWrapper.LibrarianPorterServiceServer.PushFeedItems(ctx, req)
}
}
return nil, errors.BadRequest("Unsupported notify destination", "")
}