-
Notifications
You must be signed in to change notification settings - Fork 699
/
fetcher.go
282 lines (250 loc) · 8.54 KB
/
fetcher.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
package http_fetcher
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/prebid/prebid-server/stored_requests"
jsonpatch "gopkg.in/evanphx/json-patch.v4"
"github.com/golang/glog"
"golang.org/x/net/context/ctxhttp"
)
// NewFetcher returns a Fetcher which uses the Client to pull data from the endpoint.
//
// This file expects the endpoint to satisfy the following API:
//
// Stored requests
// GET {endpoint}?request-ids=["req1","req2"]&imp-ids=["imp1","imp2","imp3"]
//
// Accounts
// GET {endpoint}?account-ids=["acc1","acc2"]
//
// The above endpoints should return a payload like:
//
// {
// "requests": {
// "req1": { ... stored data for req1 ... },
// "req2": { ... stored data for req2 ... },
// },
// "imps": {
// "imp1": { ... stored data for imp1 ... },
// "imp2": { ... stored data for imp2 ... },
// "imp3": null // If imp3 is not found
// }
// }
//
// or
//
// {
// "accounts": {
// "acc1": { ... config data for acc1 ... },
// "acc2": { ... config data for acc2 ... },
// },
// }
func NewFetcher(client *http.Client, endpoint string) *HttpFetcher {
// Do some work up-front to figure out if the (configurable) endpoint has a query string or not.
// When we build requests, we'll either want to add `?request-ids=...&imp-ids=...` _or_
// `&request-ids=...&imp-ids=...`.
if _, err := url.Parse(endpoint); err != nil {
glog.Fatalf(`Invalid endpoint "%s": %v`, endpoint, err)
}
glog.Infof("Making http_fetcher for endpoint %v", endpoint)
urlPrefix := endpoint
if strings.Contains(endpoint, "?") {
urlPrefix = urlPrefix + "&"
} else {
urlPrefix = urlPrefix + "?"
}
return &HttpFetcher{
client: client,
Endpoint: urlPrefix,
}
}
type HttpFetcher struct {
client *http.Client
Endpoint string
Categories map[string]map[string]stored_requests.Category
}
func (fetcher *HttpFetcher) FetchRequests(ctx context.Context, requestIDs []string, impIDs []string) (requestData map[string]json.RawMessage, impData map[string]json.RawMessage, errs []error) {
if len(requestIDs) == 0 && len(impIDs) == 0 {
return nil, nil, nil
}
httpReq, err := buildRequest(fetcher.Endpoint, requestIDs, impIDs)
if err != nil {
return nil, nil, []error{err}
}
httpResp, err := ctxhttp.Do(ctx, fetcher.client, httpReq)
if err != nil {
return nil, nil, []error{err}
}
defer httpResp.Body.Close()
requestData, impData, errs = unpackResponse(httpResp)
return
}
func (fetcher *HttpFetcher) FetchResponses(ctx context.Context, ids []string) (data map[string]json.RawMessage, errs []error) {
return nil, nil
}
// FetchAccounts retrieves account configurations
//
// Request format is similar to the one for requests:
// GET {endpoint}?account-ids=["account1","account2",...]
//
// The endpoint is expected to respond with a JSON map with accountID -> json.RawMessage
//
// {
// "account1": { ... account json ... }
// }
//
// The JSON contents of account config is returned as-is (NOT validated)
func (fetcher *HttpFetcher) FetchAccounts(ctx context.Context, accountIDs []string) (map[string]json.RawMessage, []error) {
if len(accountIDs) == 0 {
return nil, nil
}
httpReq, err := http.NewRequestWithContext(ctx, "GET", fetcher.Endpoint+"account-ids=[\""+strings.Join(accountIDs, "\",\"")+"\"]", nil)
if err != nil {
return nil, []error{
fmt.Errorf(`Error fetching accounts %v via http: build request failed with %v`, accountIDs, err),
}
}
httpResp, err := ctxhttp.Do(ctx, fetcher.client, httpReq)
if err != nil {
return nil, []error{
fmt.Errorf(`Error fetching accounts %v via http: %v`, accountIDs, err),
}
}
defer httpResp.Body.Close()
respBytes, err := io.ReadAll(httpResp.Body)
if err != nil {
return nil, []error{
fmt.Errorf(`Error fetching accounts %v via http: error reading response: %v`, accountIDs, err),
}
}
if httpResp.StatusCode != http.StatusOK {
return nil, []error{
fmt.Errorf(`Error fetching accounts %v via http: unexpected response status %d`, accountIDs, httpResp.StatusCode),
}
}
var responseData accountsResponseContract
if err = json.Unmarshal(respBytes, &responseData); err != nil {
return nil, []error{
fmt.Errorf(`Error fetching accounts %v via http: failed to parse response: %v`, accountIDs, err),
}
}
errs := convertNullsToErrs(responseData.Accounts, "Account", []error{})
return responseData.Accounts, errs
}
// FetchAccount fetchers a single accountID and returns its corresponding json
func (fetcher *HttpFetcher) FetchAccount(ctx context.Context, accountDefaultsJSON json.RawMessage, accountID string) (accountJSON json.RawMessage, errs []error) {
accountData, errs := fetcher.FetchAccounts(ctx, []string{accountID})
if len(errs) > 0 {
return nil, errs
}
accountJSON, ok := accountData[accountID]
if !ok {
return nil, []error{stored_requests.NotFoundError{
ID: accountID,
DataType: "Account",
}}
}
completeJSON, err := jsonpatch.MergePatch(accountDefaultsJSON, accountJSON)
if err != nil {
return nil, []error{err}
}
return completeJSON, nil
}
func (fetcher *HttpFetcher) FetchCategories(ctx context.Context, primaryAdServer, publisherId, iabCategory string) (string, error) {
if fetcher.Categories == nil {
fetcher.Categories = make(map[string]map[string]stored_requests.Category)
}
//in NewFetcher function there is a code to add "?" at the end of url
//in case of categories we don't expect to have any parameters, that's why we need to remove "?"
var dataName, url string
if publisherId != "" {
dataName = fmt.Sprintf("%s_%s", primaryAdServer, publisherId)
url = fmt.Sprintf("%s/%s/%s.json", strings.TrimSuffix(fetcher.Endpoint, "?"), primaryAdServer, publisherId)
} else {
dataName = primaryAdServer
url = fmt.Sprintf("%s/%s.json", strings.TrimSuffix(fetcher.Endpoint, "?"), primaryAdServer)
}
if data, ok := fetcher.Categories[dataName]; ok {
if val, ok := data[iabCategory]; ok {
return val.Id, nil
} else {
return "", fmt.Errorf("Unable to find category mapping for adserver: '%s', publisherId: '%s'", primaryAdServer, publisherId)
}
}
httpReq, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
httpResp, err := ctxhttp.Do(ctx, fetcher.client, httpReq)
if err != nil {
return "", err
}
defer httpResp.Body.Close()
respBytes, err := io.ReadAll(httpResp.Body)
tmp := make(map[string]stored_requests.Category)
if err := json.Unmarshal(respBytes, &tmp); err != nil {
return "", fmt.Errorf("Unable to unmarshal categories for adserver: '%s', publisherId: '%s'", primaryAdServer, publisherId)
}
fetcher.Categories[dataName] = tmp
if val, ok := tmp[iabCategory]; ok {
return val.Id, nil
} else {
return "", fmt.Errorf("Unable to find category mapping for adserver: '%s', publisherId: '%s'", primaryAdServer, publisherId)
}
}
func buildRequest(endpoint string, requestIDs []string, impIDs []string) (*http.Request, error) {
if len(requestIDs) > 0 && len(impIDs) > 0 {
return http.NewRequest("GET", endpoint+"request-ids=[\""+strings.Join(requestIDs, "\",\"")+"\"]&imp-ids=[\""+strings.Join(impIDs, "\",\"")+"\"]", nil)
} else if len(requestIDs) > 0 {
return http.NewRequest("GET", endpoint+"request-ids=[\""+strings.Join(requestIDs, "\",\"")+"\"]", nil)
} else {
return http.NewRequest("GET", endpoint+"imp-ids=[\""+strings.Join(impIDs, "\",\"")+"\"]", nil)
}
}
func unpackResponse(resp *http.Response) (requestData map[string]json.RawMessage, impData map[string]json.RawMessage, errs []error) {
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
errs = append(errs, err)
return
}
if resp.StatusCode == http.StatusOK {
var responseObj responseContract
if err := json.Unmarshal(respBytes, &responseObj); err != nil {
errs = append(errs, err)
return
}
requestData = responseObj.Requests
impData = responseObj.Imps
errs = convertNullsToErrs(requestData, "Request", errs)
errs = convertNullsToErrs(impData, "Imp", errs)
return
}
errs = append(errs, fmt.Errorf("Error fetching Stored Requests via HTTP. Response code was %d", resp.StatusCode))
return
}
func convertNullsToErrs(m map[string]json.RawMessage, dataType string, errs []error) []error {
for id, val := range m {
if bytes.Equal(val, []byte("null")) {
delete(m, id)
errs = append(errs, stored_requests.NotFoundError{
ID: id,
DataType: dataType,
})
}
}
return errs
}
// responseContract is used to unmarshal for the endpoint
type responseContract struct {
Requests map[string]json.RawMessage `json:"requests"`
Imps map[string]json.RawMessage `json:"imps"`
}
type accountsResponseContract struct {
Accounts map[string]json.RawMessage `json:"accounts"`
}