forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestful_test.go
552 lines (496 loc) · 16.7 KB
/
restful_test.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) 2017-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"sync"
"sync/atomic"
"testing"
"time"
)
func postTestError(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: []byte{0x12, 0x34}},
}, errors.New("failed to run post method")
}
func postTestSuccessButInvalidJSON(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: []byte{0x12, 0x34}},
}, nil
}
func postTestAppBadGatewayError(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusBadGateway,
Body: &fakeResponseBody{body: []byte{0x12, 0x34}},
}, nil
}
func postTestAppForbiddenError(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusForbidden,
Body: &fakeResponseBody{body: []byte{0x12, 0x34}},
}, nil
}
func postTestAppUnexpectedError(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusInsufficientStorage,
Body: &fakeResponseBody{body: []byte{0x12, 0x34}},
}, nil
}
func postTestQueryNotExecuting(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
dd := &execResponseData{}
er := &execResponse{
Data: *dd,
Message: "",
Code: queryNotExecuting,
Success: false,
}
ba, err := json.Marshal(er)
if err != nil {
panic(err)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: ba},
}, nil
}
func postTestRenew(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
dd := &execResponseData{}
er := &execResponse{
Data: *dd,
Message: "",
Code: sessionExpiredCode,
Success: true,
}
ba, err := json.Marshal(er)
logger.Infof("encoded JSON: %v", ba)
if err != nil {
panic(err)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: ba},
}, nil
}
func postTestAfterRenew(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
dd := &execResponseData{}
er := &execResponse{
Data: *dd,
Message: "",
Code: "",
Success: true,
}
ba, err := json.Marshal(er)
logger.Infof("encoded JSON: %v", ba)
if err != nil {
panic(err)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: ba},
}, nil
}
func cancelTestRetry(ctx context.Context, sr *snowflakeRestful, requestID UUID, timeout time.Duration) error {
ctxRetry := getCancelRetry(ctx)
u := url.URL{}
reqByte, err := json.Marshal(make(map[string]string))
if err != nil {
return err
}
resp, err := sr.FuncPost(ctx, sr, &u, getHeaders(), reqByte, timeout, false)
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
var respd cancelQueryResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
return err
}
if !respd.Success && respd.Code == queryNotExecuting && ctxRetry != 0 {
return sr.FuncCancelQuery(context.WithValue(ctx, cancelRetry, ctxRetry-1), sr, requestID, timeout)
}
if ctxRetry == 0 {
return nil
}
}
return fmt.Errorf("cancel retry failed")
}
func TestUnitPostQueryHelperError(t *testing.T) {
sr := &snowflakeRestful{
FuncPost: postTestError,
TokenAccessor: getSimpleTokenAccessor(),
}
var err error
requestID := NewUUID()
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, requestID, &Config{})
if err == nil {
t.Fatalf("should have failed to post")
}
sr.FuncPost = postTestAppBadGatewayError
requestID = NewUUID()
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, requestID, &Config{})
if err == nil {
t.Fatalf("should have failed to post")
}
sr.FuncPost = postTestSuccessButInvalidJSON
requestID = NewUUID()
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, requestID, &Config{})
if err == nil {
t.Fatalf("should have failed to post")
}
}
func renewSessionTest(_ context.Context, _ *snowflakeRestful, _ time.Duration) error {
return nil
}
func renewSessionTestError(_ context.Context, _ *snowflakeRestful, _ time.Duration) error {
return errors.New("failed to renew session in tests")
}
func TestUnitTokenAccessorDoesNotRenewStaleToken(t *testing.T) {
accessor := getSimpleTokenAccessor()
oldToken := "test"
accessor.SetTokens(oldToken, "master", 123)
renewSessionCalled := false
renewSessionDummy := func(_ context.Context, sr *snowflakeRestful, _ time.Duration) error {
// should not have gotten to actual renewal
renewSessionCalled = true
return nil
}
sr := &snowflakeRestful{
FuncRenewSession: renewSessionDummy,
TokenAccessor: accessor,
}
// try to intentionally renew with stale token
sr.renewExpiredSessionToken(context.Background(), time.Hour, "stale-token")
if renewSessionCalled {
t.Fatal("FuncRenewSession should not have been called")
}
// set the current token to empty, should still call renew even if stale token is passed in
accessor.SetTokens("", "master", 123)
sr.renewExpiredSessionToken(context.Background(), time.Hour, "stale-token")
if !renewSessionCalled {
t.Fatal("FuncRenewSession should have been called because current token is empty")
}
}
type wrappedAccessor struct {
ta TokenAccessor
lockCallCount int32
unlockCallCount int32
}
func (wa *wrappedAccessor) Lock() error {
atomic.AddInt32(&wa.lockCallCount, 1)
err := wa.ta.Lock()
return err
}
func (wa *wrappedAccessor) Unlock() {
atomic.AddInt32(&wa.unlockCallCount, 1)
wa.ta.Unlock()
}
func (wa *wrappedAccessor) GetTokens() (token string, masterToken string, sessionID int64) {
return wa.ta.GetTokens()
}
func (wa *wrappedAccessor) SetTokens(token string, masterToken string, sessionID int64) {
wa.ta.SetTokens(token, masterToken, sessionID)
}
func TestUnitTokenAccessorRenewBlocked(t *testing.T) {
accessor := wrappedAccessor{
ta: getSimpleTokenAccessor(),
}
oldToken := "test"
accessor.SetTokens(oldToken, "master", 123)
renewSessionCalled := false
renewSessionDummy := func(_ context.Context, sr *snowflakeRestful, _ time.Duration) error {
renewSessionCalled = true
return nil
}
sr := &snowflakeRestful{
FuncRenewSession: renewSessionDummy,
TokenAccessor: &accessor,
}
// intentionally lock the accessor first
accessor.Lock()
// try to intentionally renew with stale token
var renewalStart sync.WaitGroup
var renewalDone sync.WaitGroup
renewalStart.Add(1)
renewalDone.Add(1)
go func() {
renewalStart.Done()
sr.renewExpiredSessionToken(context.Background(), time.Hour, oldToken)
renewalDone.Done()
}()
// wait for renewal to start and get blocked on lock
renewalStart.Wait()
// should be blocked and not be able to call renew session
if renewSessionCalled {
t.Fail()
}
// rotate the token again so that the session token is considered stale
accessor.SetTokens("new-token", "m", 321)
// unlock so that renew can happen
accessor.Unlock()
renewalDone.Wait()
// renewal should be done but token should still not
// have been renewed since we intentionally swapped token while locked
if renewSessionCalled {
t.Fail()
}
// wait for accessor defer unlock
accessor.Lock()
if accessor.lockCallCount != 3 {
t.Fatalf("Expected Lock() to be called thrice, but got %v", accessor.lockCallCount)
}
if accessor.unlockCallCount != 2 {
t.Fatalf("Expected Unlock() to be called twice, but got %v", accessor.unlockCallCount)
}
}
func TestUnitTokenAccessorRenewSessionContention(t *testing.T) {
accessor := getSimpleTokenAccessor()
oldToken := "test"
accessor.SetTokens(oldToken, "master", 123)
var counter int32 = 0
expectedToken := "new token"
expectedMaster := "new master"
expectedSession := int64(321)
renewSessionDummy := func(_ context.Context, sr *snowflakeRestful, _ time.Duration) error {
accessor.SetTokens(expectedToken, expectedMaster, expectedSession)
atomic.AddInt32(&counter, 1)
return nil
}
sr := &snowflakeRestful{
FuncRenewSession: renewSessionDummy,
TokenAccessor: accessor,
}
var renewalsStart sync.WaitGroup
var renewalsDone sync.WaitGroup
var renewalError error
numRoutines := 50
for i := 0; i < numRoutines; i++ {
renewalsDone.Add(1)
renewalsStart.Add(1)
go func() {
// wait for all goroutines to have been created before proceeding to race against each other
renewalsStart.Wait()
err := sr.renewExpiredSessionToken(context.Background(), time.Hour, oldToken)
if err != nil {
renewalError = err
}
renewalsDone.Done()
}()
}
// unlock all of the waiting goroutines simultaneously
renewalsStart.Add(-numRoutines)
// wait for all competing goroutines to finish calling renew expired session token
renewalsDone.Wait()
if renewalError != nil {
t.Fatalf("failed to renew session, error %v", renewalError)
}
newToken, newMaster, newSession := accessor.GetTokens()
if newToken != expectedToken {
t.Fatalf("token %v does not match expected %v", newToken, expectedToken)
}
if newMaster != expectedMaster {
t.Fatalf("master token %v does not match expected %v", newMaster, expectedMaster)
}
if newSession != expectedSession {
t.Fatalf("session %v does not match expected %v", newSession, expectedSession)
}
// only the first renewal will go through and FuncRenewSession should be called exactly once
if counter != 1 {
t.Fatalf("renew expired session was called more than once: %v", counter)
}
}
func TestUnitPostQueryHelperUsesToken(t *testing.T) {
accessor := getSimpleTokenAccessor()
token := "token123"
accessor.SetTokens(token, "", 0)
var err error
postQueryTest := func(_ context.Context, _ *snowflakeRestful, _ *url.Values, headers map[string]string, _ []byte, _ time.Duration, _ UUID, _ *Config) (*execResponse, error) {
if headers[headerAuthorizationKey] != fmt.Sprintf(headerSnowflakeToken, token) {
t.Fatalf("authorization key doesn't match, %v vs %v", headers[headerAuthorizationKey], fmt.Sprintf(headerSnowflakeToken, token))
}
dd := &execResponseData{}
return &execResponse{
Data: *dd,
Message: "",
Code: "0",
Success: true,
}, nil
}
sr := &snowflakeRestful{
FuncPost: postTestRenew,
FuncPostQuery: postQueryTest,
FuncRenewSession: renewSessionTest,
TokenAccessor: accessor,
}
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, NewUUID(), &Config{})
if err != nil {
t.Fatalf("err: %v", err)
}
}
func TestUnitPostQueryHelperRenewSession(t *testing.T) {
var err error
origRequestID := NewUUID()
postQueryTest := func(_ context.Context, _ *snowflakeRestful, _ *url.Values, _ map[string]string, _ []byte, _ time.Duration, requestID UUID, _ *Config) (*execResponse, error) {
// ensure the same requestID is used after the session token is renewed.
if requestID != origRequestID {
t.Fatal("requestID doesn't match")
}
dd := &execResponseData{}
return &execResponse{
Data: *dd,
Message: "",
Code: "0",
Success: true,
}, nil
}
sr := &snowflakeRestful{
FuncPost: postTestRenew,
FuncPostQuery: postQueryTest,
FuncRenewSession: renewSessionTest,
TokenAccessor: getSimpleTokenAccessor(),
}
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, origRequestID, &Config{})
if err != nil {
t.Fatalf("err: %v", err)
}
sr.FuncRenewSession = renewSessionTestError
_, err = postRestfulQueryHelper(context.Background(), sr, &url.Values{}, make(map[string]string), []byte{0x12, 0x34}, 0, origRequestID, &Config{})
if err == nil {
t.Fatal("should have failed to renew session")
}
}
func TestUnitRenewRestfulSession(t *testing.T) {
accessor := getSimpleTokenAccessor()
oldToken, oldMasterToken, oldSessionID := "oldtoken", "oldmaster", int64(100)
newToken, newMasterToken, newSessionID := "newtoken", "newmaster", int64(200)
postTestSuccessWithNewTokens := func(_ context.Context, _ *snowflakeRestful, _ *url.URL, headers map[string]string, _ []byte, _ time.Duration, _ bool) (*http.Response, error) {
if headers[headerAuthorizationKey] != fmt.Sprintf(headerSnowflakeToken, oldMasterToken) {
t.Fatalf("authorization key doesn't match, %v vs %v", headers[headerAuthorizationKey], fmt.Sprintf(headerSnowflakeToken, oldMasterToken))
}
tr := &renewSessionResponse{
Data: renewSessionResponseMain{
SessionToken: newToken,
MasterToken: newMasterToken,
SessionID: newSessionID,
},
Message: "",
Success: true,
}
ba, err := json.Marshal(tr)
if err != nil {
t.Fatalf("failed to serialize token response %v", err)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: &fakeResponseBody{body: ba},
}, nil
}
sr := &snowflakeRestful{
FuncPost: postTestAfterRenew,
TokenAccessor: accessor,
}
err := renewRestfulSession(context.Background(), sr, time.Second)
if err != nil {
t.Fatalf("err: %v", err)
}
sr.FuncPost = postTestError
err = renewRestfulSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to run post request after the renewal")
}
sr.FuncPost = postTestAppBadGatewayError
err = renewRestfulSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to run post request after the renewal")
}
sr.FuncPost = postTestSuccessButInvalidJSON
err = renewRestfulSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to run post request after the renewal")
}
accessor.SetTokens(oldToken, oldMasterToken, oldSessionID)
sr.FuncPost = postTestSuccessWithNewTokens
err = renewRestfulSession(context.Background(), sr, time.Second)
if err != nil {
t.Fatal("should not have failed to run post request after the renewal")
}
token, masterToken, sessionID := accessor.GetTokens()
if token != newToken {
t.Fatalf("unexpected new token %v", token)
}
if masterToken != newMasterToken {
t.Fatalf("unexpected new master token %v", masterToken)
}
if sessionID != newSessionID {
t.Fatalf("unexpected new session id %v", sessionID)
}
}
func TestUnitCloseSession(t *testing.T) {
sr := &snowflakeRestful{
FuncPost: postTestAfterRenew,
TokenAccessor: getSimpleTokenAccessor(),
}
err := closeSession(context.Background(), sr, time.Second)
if err != nil {
t.Fatalf("err: %v", err)
}
sr.FuncPost = postTestError
err = closeSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
sr.FuncPost = postTestAppBadGatewayError
err = closeSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
sr.FuncPost = postTestSuccessButInvalidJSON
err = closeSession(context.Background(), sr, time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
}
func TestUnitCancelQuery(t *testing.T) {
sr := &snowflakeRestful{
FuncPost: postTestAfterRenew,
TokenAccessor: getSimpleTokenAccessor(),
}
ctx := context.Background()
err := cancelQuery(ctx, sr, getOrGenerateRequestIDFromContext(ctx), time.Second)
if err != nil {
t.Fatalf("err: %v", err)
}
sr.FuncPost = postTestError
err = cancelQuery(ctx, sr, getOrGenerateRequestIDFromContext(ctx), time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
sr.FuncPost = postTestAppBadGatewayError
err = cancelQuery(context.Background(), sr, getOrGenerateRequestIDFromContext(ctx), time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
sr.FuncPost = postTestSuccessButInvalidJSON
err = cancelQuery(context.Background(), sr, getOrGenerateRequestIDFromContext(ctx), time.Second)
if err == nil {
t.Fatal("should have failed to close session")
}
}
func TestCancelRetry(t *testing.T) {
sr := &snowflakeRestful{
TokenAccessor: getSimpleTokenAccessor(),
FuncPost: postTestQueryNotExecuting,
FuncCancelQuery: cancelTestRetry,
}
ctx := context.Background()
err := cancelQuery(ctx, sr, getOrGenerateRequestIDFromContext(ctx), time.Second)
if err != nil {
t.Fatal(err)
}
}