-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsumer.go
322 lines (263 loc) · 7.69 KB
/
consumer.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
package proxy
//Copyright 2016 MediaMath <http://www.mediamath.com>. All rights reserved.
//Use of this source code is governed by a BSD-style
//license that can be found in the LICENSE file.
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
)
type (
//HTTPClient is any client that can do a http request
HTTPClient interface {
Do(request *http.Request) (*http.Response, error)
}
//Message is a single kafka message
Message struct {
Key json.RawMessage `json:"key"`
Value json.RawMessage `json:"value"`
Partition int32 `json:"partition"`
Offset int64 `json:"offset"`
}
//ConsumerRequest is the meta information needed to create a consumer
ConsumerRequest struct {
Format Format `json:"format"`
Offset Offset `json:"auto.offset.reset"`
AutoCommit string `json:"auto.commit.enable"`
Name string `json:"name,omitempty"`
}
//ConsumerEndpoint is returned on a create
ConsumerEndpoint struct {
InstanceID string `json:"instance_id"`
BaseURI string `json:"base_uri"`
}
//Format is one of json, binary or avro
Format string
//Offset is either smallest or largest
Offset string
)
const (
//JSON formated consumer
JSON = Format("json")
//Binary formated consumer
Binary = Format("binary")
//Avro formated consumer
Avro = Format("avro")
//Smallest is the offset that is oldest
Smallest = "smallest"
//Largest is the offset that is newest
Largest = "largest"
)
//Consume takes a kafka location and consumes messages for it
func Consume(client HTTPClient, baseURL string, topic string, partition int32, offset int64, count int, format Format) ([]*Message, error) {
if count < 1 {
return nil, fmt.Errorf("Count must be 1 or greater: %v", count)
}
req, err := ConsumeRequest(baseURL, topic, partition, offset, count, format)
if err != nil {
return nil, err
}
resp := []*Message{}
status, body, err := doJSON(client, req, &resp)
if status != http.StatusOK {
return nil, fmt.Errorf("%v:%s", status, body)
}
if err != nil {
return nil, fmt.Errorf("%v:%s:%v", status, body, err)
}
return resp, nil
}
//ConsumeRequest builds the request for the /topics/<topic>/partitions/<partition>/messages route
func ConsumeRequest(baseURL string, topic string, partition int32, offset int64, count int, format Format) (*http.Request, error) {
contentType, err := contentTypeForFormat(format)
if err != nil {
return nil, err
}
countQuery := url.QueryEscape(fmt.Sprintf("%v", count))
offsetQuery := url.QueryEscape(fmt.Sprintf("%v", offset))
return get(
baseURL,
path.Join("topics", topic, "partitions", fmt.Sprintf("%v", partition), "messages"),
fmt.Sprintf("offset=%s&count=%s", offsetQuery, countQuery),
contentType,
)
}
//NewConsumerRequest creates a consumer request for the provided format and offset
func NewConsumerRequest(format Format, offset Offset) *ConsumerRequest {
return &ConsumerRequest{
Format: format,
Offset: offset,
AutoCommit: "true",
}
}
//CreateConsumer will create a consumer on the proxy for later use
func CreateConsumer(client HTTPClient, baseURL string, group string, request *ConsumerRequest) (resp *ConsumerEndpoint, err error) {
var req *http.Request
req, err = CreateConsumerRequest(baseURL, group, request)
if err != nil {
return
}
resp = &ConsumerEndpoint{}
var status int
var body []byte
status, body, err = doJSON(client, req, resp)
if err != nil {
return
}
if status != http.StatusOK {
err = fmt.Errorf("%v:%s", status, body)
resp = nil
return
}
return
}
//CreateConsumerRequest will create a request for the /consumers/<group> endpoint
func CreateConsumerRequest(baseURL string, group string, request *ConsumerRequest) (*http.Request, error) {
return post(baseURL, path.Join("consumers", group), request, "application/vnd.kafka.v1+json")
}
//ConsumeEndpoint will get the next messages off of the previously created consumer endpoint. Format must match the previously created format
func ConsumeEndpoint(client HTTPClient, endpoint *ConsumerEndpoint, topic string, format Format) ([]*Message, error) {
req, err := ConsumeEndpointRequest(endpoint, topic, format)
if err != nil {
return nil, err
}
resp := []*Message{}
status, body, err := doJSON(client, req, &resp)
if err != nil {
return nil, fmt.Errorf("%v:%s:%v", status, body, err)
}
if status != http.StatusOK {
return nil, fmt.Errorf("%v:%s", status, body)
}
return resp, nil
}
//ConsumeEndpointRequest will create a request for consumerURL/topics/<topic>
func ConsumeEndpointRequest(consumer *ConsumerEndpoint, topic string, format Format) (*http.Request, error) {
contentType, err := contentTypeForFormat(format)
if err != nil {
return nil, err
}
return get(consumer.BaseURI, path.Join("topics", topic), "", contentType)
}
//DeleteConsumerEndpoint will delete a previously created consumer endpoint
func DeleteConsumerEndpoint(client HTTPClient, endpoint *ConsumerEndpoint) error {
req, err := http.NewRequest("DELETE", endpoint.BaseURI, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
status := resp.StatusCode
if err != nil {
return err
}
if status != http.StatusNoContent {
return fmt.Errorf("%v:%s", status, body)
}
return nil
}
//WaitFor will return all the messages up to the timeout or count
func WaitFor(client HTTPClient, endpoint *ConsumerEndpoint, topic string, format Format, count int, timeout time.Duration) ([]*Message, error) {
messages, err := ConsumeEndpoint(client, endpoint, topic, format)
if err != nil {
return nil, err
}
timedout := make(chan error)
go func() {
<-time.After(timeout)
close(timedout)
}()
for len(messages) < count {
select {
case <-timedout:
return nil, fmt.Errorf("Timed out: %v", len(messages))
default:
<-time.After(500 * time.Millisecond)
}
more, err := ConsumeEndpoint(client, endpoint, topic, format)
if err != nil {
return nil, err
}
messages = append(messages, more...)
}
return messages, nil
}
func doJSON(restful HTTPClient, request *http.Request, response interface{}) (status int, body []byte, err error) {
res, err := restful.Do(request)
if err == nil {
body, err = ioutil.ReadAll(res.Body)
res.Body.Close()
status = res.StatusCode
}
if err == nil && response != nil {
err = json.Unmarshal(body, response)
}
return
}
func get(baseURL, path, query, accepts string) (request *http.Request, err error) {
var u string
u, err = buildURL(baseURL, path, query)
if err != nil {
return
}
request, err = http.NewRequest("GET", u, nil)
if request != nil {
request.Header.Add("Accept", accepts)
}
return
}
func post(baseURL, path string, body interface{}, contentType string) (request *http.Request, err error) {
var reader io.Reader
if body != nil {
var data []byte
data, err = json.Marshal(body)
if err != nil {
return
}
reader = bytes.NewBuffer(data)
}
var u string
u, err = buildURL(baseURL, path, "")
if err != nil {
return
}
request, err = http.NewRequest("POST", u, reader)
if request != nil {
request.Header.Add("Content-Type", contentType)
}
return
}
func contentTypeForFormat(format Format) (contentType string, err error) {
switch format {
case JSON:
contentType = "application/vnd.kafka.json.v1+json"
case Binary:
contentType = "application/vnd.kafka.binary.v1+json"
case Avro:
contentType = "application/vnd.kafka.avro.v1+json"
default:
err = fmt.Errorf("Unknown format: %v", format)
}
return
}
func buildURL(baseURL, p string, query string) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
u.Path = path.Join(u.Path, p)
if query != "" {
u.RawQuery = query
}
return u.String(), nil
}