forked from janivihervas/contentful-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
248 lines (208 loc) · 7.18 KB
/
search.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
package contentful
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"go.opencensus.io/trace"
)
var (
// ErrNoEntries is returned if no entries were returned
ErrNoEntries = errors.New("contentful: no entries returned")
// ErrMoreThanOneEntry is returned if there were more than one entry returned
ErrMoreThanOneEntry = errors.New("contentful: more then one entry was returned")
// ErrTooManyRequests is returned if hit Contentful rate limit and context doesn't have a deadline set
ErrTooManyRequests = errors.New("contentful: too many requests")
)
// GetMany entries from Contentful. The flattened json output will be marshaled into data parameter,
// which will need to be a slice or an array. Will return an error if zero entries were returned
//
// Will retry if Contentful rate limits the request if
// - context has a deadline/timeout set and
// - seconds to wait is not after context's deadline/timeout, making this fail early
func (cms *Contentful) GetMany(ctx context.Context, parameters SearchParameters, data interface{}) error {
ctx, span := trace.StartSpan(ctx, "github.com/janivihervas/contentful-go.GetMany")
defer span.End()
response, err := cms.search(ctx, parameters)
if err != nil {
addSpanError(span, trace.StatusCodeUnknown, err)
return err
}
if response.Total == 0 || len(response.Items) == 0 {
addSpanError(span, trace.StatusCodeNotFound, ErrNoEntries)
return ErrNoEntries
}
_, spanParse := trace.StartSpan(ctx, "github.com/janivihervas/contentful-go.parse")
defer spanParse.End()
appendIncludes(&response)
flattenedItems, err := flattenItems(response.Includes, response.Items)
if err != nil {
addSpanError(spanParse, trace.StatusCodeUnknown, err)
addSpanError(span, trace.StatusCodeUnknown, err)
return err
}
bytes, err := json.Marshal(flattenedItems)
if err != nil {
addSpanError(spanParse, trace.StatusCodeInternal, err)
addSpanError(span, trace.StatusCodeInternal, err)
return err
}
err = json.Unmarshal(bytes, data)
if err != nil {
addSpanError(spanParse, trace.StatusCodeInternal, err)
addSpanError(span, trace.StatusCodeInternal, err)
return err
}
return nil
}
// GetOne entry from Contentful. The flattened json output will be marshaled into data parameter.
// Will return an error if there is not exactly one entry returned
//
// Will retry if Contentful rate limits the request if
// - context has a deadline/timeout set and
// - seconds to wait is not after context's deadline/timeout, making this fail early
func (cms *Contentful) GetOne(ctx context.Context, parameters SearchParameters, data interface{}) error {
ctx, span := trace.StartSpan(ctx, "github.com/janivihervas/contentful-go.GetOne")
defer span.End()
response, err := cms.search(ctx, parameters)
if err != nil {
addSpanError(span, trace.StatusCodeUnknown, err)
return err
}
if response.Total == 0 || len(response.Items) == 0 {
addSpanError(span, trace.StatusCodeNotFound, ErrNoEntries)
return ErrNoEntries
}
if response.Total != 1 || len(response.Items) != 1 {
addSpanError(span, trace.StatusCodeOutOfRange, ErrMoreThanOneEntry)
return ErrMoreThanOneEntry
}
_, spanParse := trace.StartSpan(ctx, "github.com/janivihervas/contentful-go.parse")
defer spanParse.End()
appendIncludes(&response)
flattenedItem, err := flattenItem(response.Includes, response.Items[0])
if err != nil {
addSpanError(spanParse, trace.StatusCodeUnknown, err)
addSpanError(span, trace.StatusCodeUnknown, err)
return err
}
bytes, err := json.Marshal(flattenedItem)
if err != nil {
addSpanError(spanParse, trace.StatusCodeInternal, err)
addSpanError(span, trace.StatusCodeInternal, err)
return err
}
err = json.Unmarshal(bytes, data)
if err != nil {
addSpanError(spanParse, trace.StatusCodeInternal, err)
addSpanError(span, trace.StatusCodeInternal, err)
return err
}
return nil
}
func (cms *Contentful) search(ctx context.Context, parameters SearchParameters) (searchResults, error) {
ctx, span := trace.StartSpan(ctx, "github.com/janivihervas/contentful-go.search")
defer span.End()
response := searchResults{}
if parameters.Values == nil {
parameters.Values = url.Values{}
}
parameters.Set("include", "10")
urlStr := cms.url + "/spaces/" + cms.spaceID + "/entries?" + parameters.Encode()
urlParsed, err := url.Parse(urlStr)
if err != nil {
addSpanError(span, trace.StatusCodeInternal, err)
return response, err
}
span.AddAttributes(trace.StringAttribute("http.host", urlParsed.Host))
span.AddAttributes(trace.StringAttribute("http.method", http.MethodGet))
span.AddAttributes(trace.StringAttribute("http.path", urlParsed.Path))
span.AddAttributes(trace.StringAttribute("http.query", urlParsed.RawQuery))
req, err := http.NewRequest(http.MethodGet, urlStr, nil)
if err != nil {
addSpanError(span, trace.StatusCodeInternal, err)
return response, err
}
req.Header.Add("Authorization", "Bearer "+cms.token)
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err == context.Canceled {
addSpanError(span, trace.StatusCodeCancelled, err)
return response, err
}
if err == context.DeadlineExceeded {
addSpanError(span, trace.StatusCodeDeadlineExceeded, err)
return response, err
}
if err != nil {
addSpanError(span, trace.StatusCodeUnknown, err)
return response, err
}
defer func() {
_ = resp.Body.Close()
}()
span.AddAttributes(trace.Int64Attribute("http.status_code", int64(resp.StatusCode)))
if resp.StatusCode == http.StatusTooManyRequests {
addSpanError(span, trace.StatusCodeResourceExhausted, ErrTooManyRequests)
seconds := retryAfter(ctx, resp)
if seconds == -1 {
addSpanError(span, trace.StatusCodeDeadlineExceeded, ErrTooManyRequests)
return response, ErrTooManyRequests
}
span.AddAttributes(trace.Int64Attribute("http.ratelimit_reset", int64(seconds)))
select {
case <-time.After(time.Second * time.Duration(seconds)):
return cms.search(ctx, parameters)
case <-ctx.Done():
addSpanError(span, trace.StatusCodeCancelled, err)
return response, ctx.Err()
}
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("non-ok status code: %d", resp.StatusCode)
addSpanError(span, trace.StatusCodeUnknown, err)
return response, err
}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
addSpanError(span, trace.StatusCodeInternal, err)
return response, err
}
return response, nil
}
func retryAfter(ctx context.Context, resp *http.Response) int {
timeUntilCancel, deadlineSet := ctx.Deadline()
if !deadlineSet {
return -1
}
var (
retrySeconds = 2
header string
)
if resp != nil {
header = resp.Header.Get("X-Contentful-RateLimit-Reset")
}
s, err := strconv.Atoi(header)
if err == nil {
retrySeconds = s
}
timeToRetry := time.Now().Add(time.Second * time.Duration(retrySeconds))
shouldRetry := timeToRetry.Before(timeUntilCancel)
if shouldRetry {
return retrySeconds
}
return -1
}
// appendIncludes will append current search results to includes object,
// because Contentful doesn't duplicate items from search results to includes.
func appendIncludes(response *searchResults) {
for _, item := range response.Items {
if item.Sys.Type == linkTypeEntry {
response.Includes.Entry = append(response.Includes.Entry, item)
}
}
}