forked from hungdv136/rio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
313 lines (257 loc) · 8.07 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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package rio
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/manabie-com/rio/internal/log"
"github.com/manabie-com/rio/internal/netkit"
fs "github.com/manabie-com/rio/internal/storage"
"github.com/manabie-com/rio/internal/types"
"github.com/manabie-com/rio/internal/util"
)
const (
createStubsPath = "/stub/create_many"
uploadFilePath = "/stub/upload"
createListRequestPath = "/incoming_request/list"
)
var (
_ Server = (*LocalServer)(nil)
_ Server = (*RemoteServer)(nil)
)
// ReplayWithRequestID replay with a set of captured request id
func ReplayWithRequestID(ids ...int64) ReplayOptionFunc {
return func(o *ReplayOption) {
o.queryOption.Ids = append(o.queryOption.Ids, ids...)
}
}
// ReplayWithLimit sets a limit
func ReplayWithLimit(limit int) ReplayOptionFunc {
return func(o *ReplayOption) {
o.queryOption.Limit = limit
}
}
// ReplayOptionFunc is function to modify replay option
type ReplayOptionFunc func(*ReplayOption)
// ReplayOption defines replaying parameter
type ReplayOption struct {
queryOption *IncomingQueryOption
}
// Server defines server interface
type Server interface {
SetNamespace(v string)
GetURL(ctx context.Context) string
Create(ctx context.Context, stubs ...*Stub) error
UploadFile(ctx context.Context, fileID string, file []byte) (string, error)
Close(ctx context.Context)
}
// LocalServer is local server for unit test
type LocalServer struct {
server *httptest.Server
stubStore StubStore
handler *Handler
fileStorage fs.FileStorage
namespace string
}
// NewLocalServer returns a new instance
func NewLocalServer() *LocalServer {
stubStore := NewStubMemory()
fileStorage := fs.NewLocalStorage(fs.LocalStorageConfig{UseTempDir: true, StoragePath: "uploaded_files"})
handler := NewHandler(stubStore, fileStorage)
mux := http.NewServeMux()
mux.HandleFunc("/", handler.Handle)
return &LocalServer{
stubStore: stubStore,
fileStorage: fileStorage,
handler: handler,
server: httptest.NewServer(mux),
}
}
// NewLocalServerWithReporter inititial a server
// Automatically clean up data when test is completed
func NewLocalServerWithReporter(t *testing.T) *LocalServer {
s := NewLocalServer()
t.Cleanup(func() { s.Close(context.Background()) })
return s
}
// WithNamespace sets namespace with chaining style
func (s *LocalServer) WithNamespace(namespace string) *LocalServer {
s.SetNamespace(namespace)
return s
}
// SetNamespace sets namespace which can be used for isolating test data for each testing
func (s *LocalServer) SetNamespace(v string) {
s.namespace = v
s.handler.namespace = v
}
// GetURL gets root url of server
func (s *LocalServer) GetURL(ctx context.Context) string {
return s.server.URL
}
// Create creates stubs in local server
func (s *LocalServer) Create(ctx context.Context, stubs ...*Stub) error {
for _, stub := range stubs {
stub.WithNamespace(s.namespace)
}
return s.stubStore.Create(ctx, stubs...)
}
// UploadFile upload file to server
func (s *LocalServer) UploadFile(ctx context.Context, fileID string, file []byte) (string, error) {
_, err := s.fileStorage.UploadFile(ctx, fileID, bytes.NewReader(file))
if err != nil {
return "", err
}
return fileID, nil
}
// GetIncomingRequests gets recorded incoming requests
func (s *LocalServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error) {
option.Namespace = s.namespace
return s.stubStore.GetIncomingRequests(ctx, option)
}
// Close clean up
func (s *LocalServer) Close(ctx context.Context) {
s.server.Close()
_ = s.fileStorage.Reset(ctx)
}
// RemoteServer communicates with remote mock server
type RemoteServer struct {
rootURL string
namespace string
shadowServer Server
}
// NewRemoteServer returns a new instance
func NewRemoteServer(rootURL string) *RemoteServer {
return &RemoteServer{rootURL: rootURL}
}
// NewRemoteServerWithReporter inititial a server
// Automatically clean up data when test is completed
func NewRemoteServerWithReporter(t *testing.T, rootURL string) *RemoteServer {
s := NewRemoteServer(rootURL)
t.Cleanup(func() { s.Close(context.Background()) })
return s
}
// WithNamespace sets namespace which can be used for isolating test data for each testing
func (s *RemoteServer) WithNamespace(namespace string) *RemoteServer {
s.SetNamespace(namespace)
return s
}
// WithShadowServer sets shadow server
func (s *RemoteServer) WithShadowServer(server Server) *RemoteServer {
s.shadowServer = server
s.shadowServer.SetNamespace(s.namespace)
return s
}
// SetNamespace sets namespace which can be used for isolating test data for each testing
func (s *RemoteServer) SetNamespace(v string) {
s.namespace = v
if s.shadowServer != nil {
s.shadowServer.SetNamespace(v)
}
}
// GetURL gets root url of server
func (s *RemoteServer) GetURL(ctx context.Context) string {
return s.rootURL
}
// Create creates stubs in remote server
func (s *RemoteServer) Create(ctx context.Context, stubs ...*Stub) error {
for _, stub := range stubs {
stub.WithNamespace(s.namespace)
}
data := types.Map{"stubs": stubs, "client": "go_sdk", "return_encoded": true}
parsedResp, err := netkit.PostJSON[netkit.InternalBody[ArrayStubs]](ctx, s.rootURL+createStubsPath, data)
if err != nil {
return err
}
if parsedResp.StatusCode != http.StatusOK {
err := errors.New("cannot create stubs")
log.Error(ctx, err)
return err
}
if s.shadowServer != nil {
return s.shadowServer.Create(ctx, parsedResp.Body.Data.Stubs...)
}
return nil
}
// UploadFile upload file to server
func (s *RemoteServer) UploadFile(ctx context.Context, fileID string, fileBody []byte) (string, error) {
request, err := netkit.NewUploadRequest(ctx, s.rootURL+uploadFilePath, fileBody, map[string]string{"file_id": fileID})
if err != nil {
return "", err
}
res, err := netkit.SendRequest(request)
if err != nil {
log.Error(ctx, err)
return "", err
}
defer util.CloseSilently(ctx, res.Body.Close)
if res == nil || res.StatusCode != http.StatusOK {
err := fmt.Errorf("cannot upload file %v", res)
log.Error(ctx, err)
return "", err
}
parsedResp, err := netkit.ParseResponse[netkit.InternalBody[types.Map]](ctx, res)
if err != nil {
log.Error(ctx, err)
return "", err
}
if s.shadowServer != nil {
if _, err := s.shadowServer.UploadFile(ctx, fileID, fileBody); err != nil {
return "", err
}
}
fileID, _ = parsedResp.Body.Data.GetString("file_id")
return fileID, nil
}
// GetIncomingRequests gets recorded incoming requests
func (s *RemoteServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error) {
option.Namespace = s.namespace
res, err := netkit.PostJSON[netkit.InternalBody[IncomingRequests]](ctx, s.rootURL+createListRequestPath, option)
if err != nil {
log.Error(ctx, err)
return nil, err
}
if res.StatusCode != http.StatusOK {
err := errors.New("cannot get incoming requests")
log.Error(ctx, err)
return nil, err
}
return res.Body.Data.Requests, nil
}
// ReplayOnShadowServer replays incoming requests (from remote server) to a shadow server (local server)
// By default, only the last request will be replayed. Use option to change replay option
// This is to debug the stub on a remote server using IDE
func (s *RemoteServer) ReplayOnShadowServer(ctx context.Context, options ...ReplayOptionFunc) error {
if s.shadowServer == nil {
err := errors.New("shawdow server has not set")
log.Error(ctx, err)
return err
}
relayOpt := &ReplayOption{
queryOption: &IncomingQueryOption{
Namespace: s.namespace,
Limit: 1,
},
}
for _, optionFn := range options {
optionFn(relayOpt)
}
requests, err := s.GetIncomingRequests(ctx, relayOpt.queryOption)
if err != nil {
return err
}
log.Info(ctx, s.namespace, "nb of requests", len(requests))
for i := len(requests) - 1; i >= 0; i-- {
res, err := requests[i].Replay(ctx, s.shadowServer)
if err != nil {
return err
}
log.Info(ctx, "replayed", requests[i].ID, requests[i].URL, res.StatusCode)
res.Body.Close()
}
return nil
}
// Close clean up server data
func (s *RemoteServer) Close(ctx context.Context) {}