-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathporter.go
247 lines (229 loc) · 6.02 KB
/
porter.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
247
package tuihub
import (
"context"
"errors"
"fmt"
"os"
"sync"
"time"
porter "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/tuihub/tuihub-go/internal"
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/transport/grpc"
capi "github.com/hashicorp/consul/api"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
const (
serviceID = "PORTER_SERVICE_ID"
serverNetwork = "SERVER_NETWORK"
serverAddr = "SERVER_ADDRESS"
serverTimeout = "SERVER_TIMEOUT"
consulAddr = "CONSUL_ADDRESS"
consulToken = "CONSUL_TOKEN"
sephirahServiceName = "SEPHIRAH_SERVICE_NAME"
)
type Porter struct {
server *grpc.Server
requireAsUser bool
wrapper *serviceWrapper
logger log.Logger
app *kratos.App
consulConfig *capi.Config
serverConfig *ServerConfig
}
type ServerConfig struct {
Network string
Addr string
Timeout *time.Duration
}
type PorterOption func(*Porter)
func WithLogger(logger log.Logger) PorterOption {
return func(p *Porter) {
p.logger = logger
}
}
func WithPorterConsulConfig(config *capi.Config) PorterOption {
return func(p *Porter) {
p.consulConfig = config
}
}
func WithAsUser() PorterOption {
return func(p *Porter) {
p.requireAsUser = true
}
}
func (p *Porter) Run() error {
return p.app.Run()
}
func (p *Porter) Stop() error {
return p.app.Stop()
}
func NewPorter(
ctx context.Context,
info *porter.GetPorterInformationResponse,
service porter.LibrarianPorterServiceServer,
options ...PorterOption,
) (*Porter, error) {
if service == nil {
return nil, errors.New("serviceServer is nil")
}
if info.GetBinarySummary() == nil {
return nil, errors.New("binary summary is nil")
}
if info.GetGlobalName() == "" {
return nil, errors.New("global name is empty")
}
if info.GetFeatureSummary() == nil {
return nil, errors.New("feature summary is nil")
}
p := new(Porter)
p.logger = log.DefaultLogger
for _, o := range options {
o(p)
}
if p.serverConfig == nil {
p.serverConfig = defaultServerConfig()
}
if p.consulConfig == nil {
p.consulConfig = defaultConsulConfig()
}
client, err := internal.NewSephirahClient(ctx, p.consulConfig, os.Getenv(sephirahServiceName))
if err != nil {
return nil, err
}
r, err := internal.NewRegistry(p.consulConfig)
if err != nil {
return nil, err
}
c := &serviceWrapper{
LibrarianPorterServiceServer: service,
Info: info,
Logger: p.logger,
Client: client,
RequireToken: p.requireAsUser,
Token: nil,
tokenMu: sync.Mutex{},
lastHeartbeat: time.Time{},
lastRefreshToken: time.Time{},
}
p.wrapper = c
p.server = NewServer(
p.serverConfig,
NewService(c),
p.logger,
)
id, _ := os.Hostname()
name := "porter"
id = fmt.Sprintf("%s-%s-%s", id, name, info.GetBinarySummary().GetName())
if customID, exist := os.LookupEnv(serviceID); exist {
id = fmt.Sprintf("%s-%s", id, customID)
}
app := kratos.New(
kratos.ID(id),
kratos.Name(name),
kratos.Version(p.wrapper.Info.GetBinarySummary().GetBuildVersion()),
kratos.Metadata(map[string]string{
"PorterName": p.wrapper.Info.GetGlobalName(),
}),
kratos.Server(p.server),
kratos.Registrar(r),
)
p.app = app
return p, nil
}
func defaultServerConfig() *ServerConfig {
config := ServerConfig{
Network: "",
Addr: "",
Timeout: nil,
}
if network, exist := os.LookupEnv(serverNetwork); exist {
config.Network = network
}
if addr, exist := os.LookupEnv(serverAddr); exist {
config.Addr = addr
}
if timeout, exist := os.LookupEnv(serverTimeout); exist {
d, err := time.ParseDuration(timeout)
if err == nil {
config.Timeout = &d
}
}
return &config
}
func defaultConsulConfig() *capi.Config {
config := capi.DefaultConfig()
if addr, exist := os.LookupEnv(consulAddr); exist {
config.Address = addr
}
if token, exist := os.LookupEnv(consulToken); exist {
config.Token = token
}
return config
}
func WellKnownToString(e protoreflect.Enum) string {
return fmt.Sprint(proto.GetExtension(
e.
Descriptor().
Values().
ByNumber(
e.
Number(),
).
Options(),
librarian.E_ToString,
))
}
func (p *Porter) ReverseCall(ctx context.Context) (*LibrarianClient, error) {
if !p.requireAsUser {
return nil, errors.New("init porter with `WithAsUser` option to use this method")
}
if p.wrapper.Token == nil {
return nil, errors.New("porter not enabled")
}
client, err := internal.NewSephirahClient(ctx, p.consulConfig, os.Getenv(sephirahServiceName))
if err != nil {
return nil, err
}
return &LibrarianClient{
LibrarianSephirahServiceClient: client,
accessToken: p.wrapper.Token.AccessToken,
refreshToken: "",
muToken: sync.RWMutex{},
backgroundRefresh: false,
consulConfig: p.consulConfig,
}, nil
}
func (p *Porter) AsUser(ctx context.Context, userID int64) (*LibrarianClient, error) {
if !p.requireAsUser {
return nil, errors.New("init porter with `WithAsUser` option to use this method")
}
if p.wrapper.Token == nil {
return nil, errors.New("porter not enabled")
}
client, err := internal.NewSephirahClient(ctx, p.consulConfig, os.Getenv(sephirahServiceName))
if err != nil {
return nil, err
}
resp, err := client.AcquireUserToken(
WithToken(ctx, p.wrapper.Token.AccessToken),
&sephirah.AcquireUserTokenRequest{
UserId: &librarian.InternalID{Id: userID},
},
)
if err != nil {
return nil, err
}
return &LibrarianClient{
LibrarianSephirahServiceClient: client,
accessToken: resp.GetAccessToken(),
refreshToken: "",
muToken: sync.RWMutex{},
backgroundRefresh: false,
consulConfig: p.consulConfig,
}, nil
}