-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
256 lines (225 loc) · 6.05 KB
/
handlers.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
/*
Copyright 2013-2014 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License version 3, as published
by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Package api has code that offers a REST API for the applications that
// want to push messages.
package api
import (
"encoding/json"
"fmt"
"io"
"launchpad.net/ubuntu-push/logger"
"launchpad.net/ubuntu-push/server/broker"
"launchpad.net/ubuntu-push/server/store"
"net/http"
)
const MaxRequestBodyBytes = 4 * 1024
const JSONMediaType = "application/json"
// APIError represents a API error (both internally and as JSON in a response).
type APIError struct {
// http status code
StatusCode int `json:"-"`
// machine readable label
ErrorLabel string `json:"error"`
// human message
Message string `json:"message"`
}
// machine readable error labels
const (
ioError = "io-error"
invalidRequest = "invalid-request"
unknownChannel = "unknown channel"
unavailable = "unavailable"
internalError = "internal"
)
func (apiErr *APIError) Error() string {
return fmt.Sprintf("api %s: %s", apiErr.ErrorLabel, apiErr.Message)
}
// Well-known prebuilt API errors
var (
ErrNoContentLengthProvided = &APIError{
http.StatusLengthRequired,
invalidRequest,
"A Content-Length must be provided",
}
ErrRequestBodyEmpty = &APIError{
http.StatusBadRequest,
invalidRequest,
"Request body empty",
}
ErrRequestBodyTooLarge = &APIError{
http.StatusRequestEntityTooLarge,
invalidRequest,
"Request body too large",
}
ErrWrongContentType = &APIError{
http.StatusUnsupportedMediaType,
invalidRequest,
"Wrong content type, should be application/json",
}
ErrWrongRequestMethod = &APIError{
http.StatusMethodNotAllowed,
invalidRequest,
"Wrong request method, should be POST",
}
ErrMalformedJSONObject = &APIError{
http.StatusBadRequest,
invalidRequest,
"Malformed JSON Object",
}
ErrCouldNotReadBody = &APIError{
http.StatusBadRequest,
ioError,
"Could not read request body",
}
ErrMissingData = &APIError{
http.StatusBadRequest,
invalidRequest,
"Missing data field",
}
ErrUnknownChannel = &APIError{
http.StatusBadRequest,
unknownChannel,
"Unknown channel",
}
ErrUnknown = &APIError{
http.StatusInternalServerError,
internalError,
"Unknown error",
}
ErrCouldNotStoreNotification = &APIError{
http.StatusServiceUnavailable,
unavailable,
"Could not store notification",
}
)
type Message struct {
Registration string `json:"registration"`
CoalesceTag string `json:"coalesce_tag"`
Data json.RawMessage `json:"data"`
}
// Broadcast request JSON object.
type Broadcast struct {
Channel string `json:"channel"`
ExpireAfter uint8 `json:"expire_after"`
Data json.RawMessage `json:"data"`
}
func respondError(writer http.ResponseWriter, apiErr *APIError) {
wireError, err := json.Marshal(apiErr)
if err != nil {
panic(fmt.Errorf("couldn't marshal our own errors: %v", err))
}
writer.Header().Set("Content-type", JSONMediaType)
writer.WriteHeader(apiErr.StatusCode)
writer.Write(wireError)
}
func checkContentLength(request *http.Request) *APIError {
if request.ContentLength == -1 {
return ErrNoContentLengthProvided
}
if request.ContentLength == 0 {
return ErrRequestBodyEmpty
}
if request.ContentLength > MaxRequestBodyBytes {
return ErrRequestBodyTooLarge
}
return nil
}
func checkRequestAsPost(request *http.Request) *APIError {
if err := checkContentLength(request); err != nil {
return err
}
if request.Header.Get("Content-Type") != JSONMediaType {
return ErrWrongContentType
}
if request.Method != "POST" {
return ErrWrongRequestMethod
}
return nil
}
func readBody(request *http.Request) ([]byte, *APIError) {
if err := checkRequestAsPost(request); err != nil {
return nil, err
}
body := make([]byte, request.ContentLength)
_, err := io.ReadFull(request.Body, body)
if err != nil {
return nil, ErrCouldNotReadBody
}
return body, nil
}
func checkBroadcast(bcast *Broadcast) *APIError {
if len(bcast.Data) == 0 {
return ErrMissingData
}
return nil
}
// state holds the interfaces to delegate to serving requests
type state struct {
store store.PendingStore
broker broker.BrokerSending
logger logger.Logger
}
type BroadcastHandler state
func (h *BroadcastHandler) doBroadcast(bcast *Broadcast) *APIError {
apiErr := checkBroadcast(bcast)
if apiErr != nil {
return apiErr
}
chanId, err := h.store.GetInternalChannelId(bcast.Channel)
if err != nil {
switch err {
case store.ErrUnknownChannel:
return ErrUnknownChannel
default:
return ErrUnknown
}
}
// xxx ignoring expiration for now
err = h.store.AppendToChannel(chanId, bcast.Data)
if err != nil {
// assume this for now
return ErrCouldNotStoreNotification
}
h.broker.Broadcast(chanId)
return nil
}
func (h *BroadcastHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
body, apiErr := readBody(request)
if apiErr != nil {
respondError(writer, apiErr)
return
}
broadcast := &Broadcast{}
err := json.Unmarshal(body, broadcast)
if err != nil {
respondError(writer, ErrMalformedJSONObject)
return
}
apiErr = h.doBroadcast(broadcast)
if apiErr != nil {
respondError(writer, apiErr)
return
}
writer.Header().Set("Content-Type", "application/json")
fmt.Fprintf(writer, `{"ok":true}`)
}
// MakeHandlersMux makes a handler that dispatches for the various API endpoints.
func MakeHandlersMux(store store.PendingStore, broker broker.BrokerSending, logger logger.Logger) http.Handler {
mux := http.NewServeMux()
mux.Handle("/broadcast", &BroadcastHandler{
store: store,
broker: broker,
logger: logger,
})
return mux
}