-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
147 lines (127 loc) · 4.24 KB
/
server.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
package feedapi
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
// EventPublisher is a generic-based interface that has to be implemented on a server side.
type EventPublisher interface {
// GetName should return the name of the EventPublisher (used in logging).
GetName() string
GetFeedInfo() FeedInfo
EventFetcher
}
// HTTPHandlers wraps eventPublisher to provide what you need for HTTP server, implementing
// both protocols version 1 and 2. It is required that you install two handlers: DiscoveryHandler
// and FetchEventsHandler. The first one is put on an endpoint of your own choosing; the
// latter should be installed at `/events` relative to the first one.
type HTTPHandlers struct {
eventPublisher EventPublisher
loggerFromRequest func(*http.Request) logrus.FieldLogger
feedInfo FeedInfo
partitionsById map[int]Partition
}
func NewHTTPHandlers(publisher EventPublisher, loggerFromRequest func(*http.Request) logrus.FieldLogger) HTTPHandlers {
feedInfo := publisher.GetFeedInfo()
partitionsById := make(map[int]Partition)
for _, p := range feedInfo.Partitions {
partitionsById[p.Id] = p
}
return HTTPHandlers{
eventPublisher: publisher,
loggerFromRequest: loggerFromRequest,
feedInfo: feedInfo,
partitionsById: partitionsById,
}
}
// DiscoveryHandler should be handling GET requests on the main URL of your FeedAPI
// endpoint. Note: It will also serve events in v1 of the protocol.
func (h HTTPHandlers) DiscoveryHandler(writer http.ResponseWriter, request *http.Request) {
query := request.URL.Query()
if query.Has("n") {
// version 1 of the protocol, "ZeroEventHub"
h.ZeroEventHubV1Handler(writer, request)
return
}
// We are on version 2
encodedInfo, err := json.Marshal(h.eventPublisher.GetFeedInfo())
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
return
}
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write(encodedInfo)
_, _ = writer.Write([]byte("\n"))
}
func (h HTTPHandlers) EventsHandler(writer http.ResponseWriter, request *http.Request) {
partitionCount := len(h.eventPublisher.GetFeedInfo().Partitions)
logger := h.loggerFromRequest(request)
query := request.URL.Query()
if !query.Has("token") || query.Get("token") != h.feedInfo.Token {
http.Error(writer, ErrIllegalToken.Error(), ErrIllegalToken.Status())
return
}
var partitionId int
var err error
if partitionId, err = strconv.Atoi(query.Get("partition")); err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
} else if _, ok := h.partitionsById[partitionId]; !ok {
http.Error(writer, ErrPartitionDoesntExist.Error(), ErrPartitionDoesntExist.Status())
return
}
pageSizeHint := DefaultPageSize
if query.Has("pagesizehint") {
if x, err := strconv.Atoi(query.Get("pagesizehint")); err != nil {
http.Error(writer, "pagesizehint not an integer", http.StatusBadRequest)
return
} else {
pageSizeHint = x
}
}
if !query.Has("cursor") {
http.Error(writer, "no cursor argument", http.StatusBadRequest)
return
}
cursor := query.Get("cursor")
var eventTypes []string = nil
if query.Has("event-types") {
eventTypes = strings.Split(query.Get("event-types"), ";")
}
fields := logger.
WithField("event", h.eventPublisher.GetName()).
WithField("PartitionCount", partitionCount).
WithField("partitionID", partitionId).
WithField("cursors", cursor).
WithField("PageSizeHint", pageSizeHint).
WithField("EventTypes", eventTypes)
fields.Debug()
serializer := NewNDJSONEventSerializer(writer)
err = h.eventPublisher.FetchEvents(request.Context(), "", partitionId, cursor, serializer, Options{
PageSizeHint: pageSizeHint,
EventTypes: eventTypes,
})
if err != nil {
logger.WithField("publisherName", h.eventPublisher.GetName()).
WithField("event", "feedapi.server.fetch_events_error").WithError(err).Warning()
http.Error(writer, "Internal server error", http.StatusInternalServerError)
return
}
}
func parseCursors(partitionCount int, query url.Values) (cursors []Cursor) {
for i := 0; i < partitionCount; i++ {
partition := fmt.Sprintf("cursor%d", i)
if !query.Has(partition) {
continue
}
cursors = append(cursors, Cursor{
PartitionID: i,
Cursor: query.Get(partition),
})
}
return
}