forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
async.go
183 lines (171 loc) · 5.03 KB
/
async.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
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"time"
)
func (sr *snowflakeRestful) processAsync(
ctx context.Context,
respd *execResponse,
headers map[string]string,
timeout time.Duration,
cfg *Config) (*execResponse, error) {
// placeholder object to return to user while retrieving results
rows := new(snowflakeRows)
res := new(snowflakeResult)
switch resType := getResultType(ctx); resType {
case execResultType:
res.queryID = respd.Data.QueryID
res.status = QueryStatusInProgress
res.errChannel = make(chan error)
respd.Data.AsyncResult = res
case queryResultType:
rows.queryID = respd.Data.QueryID
rows.status = QueryStatusInProgress
rows.errChannel = make(chan error)
respd.Data.AsyncRows = rows
default:
return respd, nil
}
// spawn goroutine to retrieve asynchronous results
go sr.getAsync(ctx, headers, sr.getFullURL(respd.Data.GetResultURL, nil), timeout, res, rows, cfg)
return respd, nil
}
func (sr *snowflakeRestful) getAsync(
ctx context.Context,
headers map[string]string,
URL *url.URL,
timeout time.Duration,
res *snowflakeResult,
rows *snowflakeRows,
cfg *Config) error {
resType := getResultType(ctx)
var errChannel chan error
sfError := &SnowflakeError{
Number: ErrAsync,
}
if resType == execResultType {
errChannel = res.errChannel
sfError.QueryID = res.queryID
} else {
errChannel = rows.errChannel
sfError.QueryID = rows.queryID
}
defer close(errChannel)
token, _, _ := sr.TokenAccessor.GetTokens()
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, token)
respd, err := getQueryResultWithRetriesForAsyncMode(ctx, sr, URL, headers, timeout)
if err != nil {
logger.WithContext(ctx).Errorf("error: %v", err)
sfError.Message = err.Error()
errChannel <- sfError
return err
}
sc := &snowflakeConn{rest: sr, cfg: cfg, queryContextCache: (&queryContextCache{}).init(), currentTimeProvider: defaultTimeProvider}
if respd.Success {
if resType == execResultType {
res.insertID = -1
if isDml(respd.Data.StatementTypeID) {
res.affectedRows, err = updateRows(respd.Data)
if err != nil {
return err
}
} else if isMultiStmt(&respd.Data) {
r, err := sc.handleMultiExec(ctx, respd.Data)
if err != nil {
res.errChannel <- err
return err
}
res.affectedRows, err = r.RowsAffected()
if err != nil {
res.errChannel <- err
return err
}
}
res.queryID = respd.Data.QueryID
res.errChannel <- nil // mark exec status complete
} else {
rows.sc = sc
rows.queryID = respd.Data.QueryID
if isMultiStmt(&respd.Data) {
if err = sc.handleMultiQuery(ctx, respd.Data, rows); err != nil {
rows.errChannel <- err
close(rows.errChannel)
return err
}
} else {
rows.addDownloader(populateChunkDownloader(ctx, sc, respd.Data))
}
if err = rows.ChunkDownloader.start(); err != nil {
rows.errChannel <- err
close(rows.errChannel)
return err
}
rows.errChannel <- nil // mark query status complete
}
} else {
var code int
if respd.Code != "" {
code, err = strconv.Atoi(respd.Code)
if err != nil {
code = -1
}
} else {
code = -1
}
errChannel <- &SnowflakeError{
Number: code,
SQLState: respd.Data.SQLState,
Message: respd.Message,
QueryID: respd.Data.QueryID,
}
}
return nil
}
func getQueryResultWithRetriesForAsyncMode(
ctx context.Context,
sr *snowflakeRestful,
URL *url.URL,
headers map[string]string,
timeout time.Duration) (*execResponse, error) {
var respd *execResponse
retry := 0
retryPattern := []int32{1, 1, 2, 3, 4, 8, 10}
retryPatternIndex := 0
for {
logger.WithContext(ctx).Debugf("Retry count for get query result request in async mode: %v", retry)
resp, err := sr.FuncGet(ctx, sr, URL, headers, timeout)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
return respd, err
}
defer resp.Body.Close()
respd = &execResponse{} // reset the response
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
logger.WithContext(ctx).Errorf("failed to decode JSON. err: %v", err)
return respd, err
}
if respd.Code != queryInProgressAsyncCode {
// If the query takes longer than 45 seconds to complete the results are not returned.
// If the query is still in progress after 45 seconds, retry the request to the /results endpoint.
// For all other scenarios continue processing results response
break
} else {
// Sleep before retrying get result request. Exponential backoff up to 5 seconds.
// Once 5 second backoff is reached it will keep retrying with this sleeptime.
sleepTime := time.Millisecond * time.Duration(500*retryPattern[retryPatternIndex])
logger.WithContext(ctx).Infof("Query execution still in progress. Response code: %v, message: %v Sleep for %v ms", respd.Code, respd.Message, sleepTime)
time.Sleep(sleepTime)
retry++
if retryPatternIndex < len(retryPattern)-1 {
retryPatternIndex++
}
}
}
return respd, nil
}