-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
215 lines (187 loc) · 5.64 KB
/
client.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
package rest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"time"
rest "github.com/hasura/ndc-rest-schema/schema"
"github.com/hasura/ndc-sdk-go/connector"
"github.com/hasura/ndc-sdk-go/schema"
"github.com/hasura/ndc-sdk-go/utils"
)
// Doer abstracts a HTTP client with Do method
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
type httpClient struct {
Client Doer
}
func createHTTPClient(client Doer) *httpClient {
return &httpClient{
Client: client,
}
}
// Send creates and executes the request and evaluate response selection
func (client *httpClient) Send(ctx context.Context, request *RetryableRequest, selection schema.NestedField, resultType schema.Type) (any, error) {
var resp *http.Response
var err error
logger := connector.GetLogger(ctx)
if logger.Enabled(ctx, slog.LevelDebug) {
logAttrs := []any{
slog.String("request_url", request.rawRequest.URL),
slog.String("request_method", request.rawRequest.Method),
slog.Any("request_headers", request.headers),
}
if request.body != nil {
logAttrs = append(logAttrs, slog.String("request_body", request.body.String()))
}
logger.Debug("sending request to remote server...", logAttrs...)
}
times := int(request.rawRequest.Retry.Times)
for i := 0; i <= times; i++ {
req, cancel, reqError := request.CreateRequest(ctx)
if reqError != nil {
cancel()
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
resp, err = client.Client.Do(req)
if (err == nil && resp.StatusCode >= 200 && resp.StatusCode < 299) || i >= times {
break
}
if logger.Enabled(ctx, slog.LevelDebug) {
logAttrs := []any{}
if err != nil {
logAttrs = append(logAttrs, slog.Any("error", err.Error()))
} else {
logAttrs = append(logAttrs,
slog.Int("http_status", resp.StatusCode),
slog.Any("response_headers", resp.Header),
)
if resp.Body != nil {
respBody, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err == nil {
logAttrs = append(logAttrs, slog.String("response_body", string(respBody)))
}
}
}
logger.Debug(
fmt.Sprintf("received error from remote server, retrying %d time ...", i+1),
logAttrs...,
)
} else if resp.Body != nil {
_ = resp.Body.Close()
}
time.Sleep(time.Duration(request.rawRequest.Retry.Delay) * time.Millisecond)
}
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
if logger.Enabled(ctx, slog.LevelDebug) {
logAttrs := []any{
slog.Int("http_status", resp.StatusCode),
slog.Any("response_headers", resp.Header),
}
if resp.Body != nil {
respBody, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
logAttrs = append(logAttrs, slog.String("response_body", string(respBody)))
resp.Body = io.NopCloser(bytes.NewBuffer(respBody))
}
logger.Debug("received response from remote server", logAttrs...)
}
return evalHTTPResponse(resp, selection, resultType)
}
func evalHTTPResponse(resp *http.Response, selection schema.NestedField, resultType schema.Type) (any, error) {
contentType := parseContentType(resp.Header.Get(contentTypeHeader))
if resp.StatusCode >= 400 {
var respBody []byte
if resp.Body != nil {
var err error
respBody, err = io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, resp.Status, map[string]any{
"error": err,
})
}
}
return nil, schema.NewConnectorError(resp.StatusCode, resp.Status, map[string]any{
"error": string(respBody),
})
}
if resp.StatusCode == http.StatusNoContent {
return true, nil
}
if resp.Body == nil {
return nil, nil
}
defer func() {
_ = resp.Body.Close()
}()
switch contentType {
case "":
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
if len(respBody) == 0 {
return nil, nil
}
return string(respBody), nil
case "text/plain", "text/html":
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
return string(respBody), nil
case contentTypeJSON:
if len(resultType) > 0 {
namedType, err := resultType.AsNamed()
if err == nil && namedType.Name == string(rest.ScalarString) {
respBytes, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, "failed to read response", map[string]any{
"reason": err.Error(),
})
}
var strResult string
if err := json.Unmarshal(respBytes, &strResult); err != nil {
// fallback to raw string response if the result type is String
return string(respBytes), nil
}
return strResult, nil
}
}
var result any
err := json.NewDecoder(resp.Body).Decode(&result)
_ = resp.Body.Close()
if err != nil {
return nil, schema.NewConnectorError(http.StatusInternalServerError, err.Error(), nil)
}
if selection == nil || selection.IsNil() {
return result, nil
}
return utils.EvalNestedColumnFields(selection, result)
default:
return nil, schema.NewConnectorError(http.StatusInternalServerError, "failed to evaluate response", map[string]any{
"cause": fmt.Sprintf("unsupported content type %s", contentType),
})
}
}
func parseContentType(input string) string {
if input == "" {
return ""
}
parts := strings.Split(input, ";")
return strings.TrimSpace(parts[0])
}