This repository has been archived by the owner on Dec 13, 2022. It is now read-only.
/
server.go
339 lines (270 loc) · 8.35 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright © 2018 Job King'ori Maina <j@kingori.co>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package service
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/heptiolabs/healthcheck"
"github.com/satori/go.uuid"
"github.com/spf13/viper"
log "github.com/sirupsen/logrus"
)
const (
// MinRequestTTL in the minimum TTL that we should allow to be set on requests
MinRequestTTL = 300
)
type source struct {
URL string `json:"url"`
}
type renderRequest interface {
save(riq string, clt *Client) (ConversionJob, error)
sourceURL() (*url.URL, error)
fulfill(clt *Client, cj *ConversionJob, outputDir string) ([]byte, string, error)
}
type errorResponse struct {
Identifier string `json:"uuid"`
Message string `json:"message"`
}
type renderResponse struct {
Identifier string `json:"uuid"`
CreatedAt string `json:"created_at"`
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at"`
ExpiresIn int `json:"expires_in"`
FileURL string `json:"file_url"`
Status string `json:"status"`
Logs []string `json:"logs"`
}
func requestBadRequestResponse(w *http.ResponseWriter, r *http.Request, ers errorResponse) {
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Error(ers.Message)
(*w).Header().Set("Content-Type", "application/json")
(*w).WriteHeader(http.StatusBadRequest)
encoder := json.NewEncoder((*w))
encoder.SetEscapeHTML(false)
encoder.Encode(&ers)
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Errorf("%d %s", http.StatusBadRequest, "Bad Request")
}
func requestInternalServerErrorResponse(w *http.ResponseWriter, r *http.Request, ers errorResponse) {
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Error(ers.Message)
(*w).Header().Set("Content-Type", "application/json")
(*w).WriteHeader(http.StatusInternalServerError)
encoder := json.NewEncoder((*w))
encoder.SetEscapeHTML(false)
encoder.Encode(&ers)
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Errorf("%d %s", http.StatusInternalServerError, "Internal Server Error")
}
func requestNotFoundResponse(w *http.ResponseWriter, r *http.Request, ers errorResponse) {
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Error(ers.Message)
(*w).Header().Set("Content-Type", "application/json")
(*w).WriteHeader(http.StatusNotFound)
encoder := json.NewEncoder((*w))
encoder.SetEscapeHTML(false)
encoder.Encode(&ers)
log.WithFields(log.Fields{
"uuid": ers.Identifier,
}).Errorf("%d %s", http.StatusNotFound, "Not Found")
}
func requestCreatedResponse(w *http.ResponseWriter, r *http.Request, rrs renderResponse) {
(*w).Header().Set("Content-Type", "application/json")
(*w).WriteHeader(http.StatusCreated)
encoder := json.NewEncoder((*w))
encoder.SetEscapeHTML(false)
encoder.Encode(&rrs)
log.WithFields(log.Fields{
"uuid": rrs.Identifier,
}).Debugf("%d %s", http.StatusCreated, "Created")
}
func requestOKResponse(w *http.ResponseWriter, r *http.Request, rrs renderResponse) {
(*w).Header().Set("Content-Type", "application/json")
(*w).WriteHeader(http.StatusOK)
encoder := json.NewEncoder((*w))
encoder.SetEscapeHTML(false)
encoder.Encode(&rrs)
log.WithFields(log.Fields{
"uuid": rrs.Identifier,
}).Debugf("%d %s", http.StatusOK, "OK")
}
func (clt *Client) renderHandler(w http.ResponseWriter, r *http.Request) {
var (
ers errorResponse
rrq renderRequest
)
params := mux.Vars(r)
target := params["target"]
rid := uuid.NewV4().String()
switch target {
case "image":
rrq = &imageRenderRequest{}
case "pdf":
rrq = &pdfRenderRequest{}
default:
ers = errorResponse{
Identifier: rid,
Message: fmt.Sprintf("invalid %s render request", target),
}
requestBadRequestResponse(&w, r, ers)
return
}
err := json.NewDecoder(r.Body).Decode(rrq)
if err != nil {
ers = errorResponse{
Identifier: rid,
Message: fmt.Sprintf("unable to unmarshal json to %s type", target),
}
requestBadRequestResponse(&w, r, ers)
return
}
cj, err := rrq.save(rid, clt)
if err != nil {
ers = errorResponse{
Identifier: rid,
Message: fmt.Sprintf("unable to enqueue %s job", target),
}
requestInternalServerErrorResponse(&w, r, ers)
return
}
log.WithFields(log.Fields{
"uuid": cj.Identifier,
}).Infof("enqueued render %s job", target)
rrs, err := cj.generateRenderResponse(clt)
if err != nil {
ers = errorResponse{
Identifier: cj.Identifier,
Message: "failed to generate render response",
}
requestInternalServerErrorResponse(&w, r, ers)
return
}
requestCreatedResponse(&w, r, rrs)
}
func (clt *Client) statusHandler(w http.ResponseWriter, r *http.Request) {
var ers errorResponse
params := mux.Vars(r)
jid := params["uuid"]
_, err := uuid.FromString(params["uuid"])
if err != nil {
ers = errorResponse{
Identifier: jid,
Message: "invalid job identifier",
}
requestBadRequestResponse(&w, r, ers)
return
}
conn := clt.redisPool.Get()
defer conn.Close()
cj, found, err := clt.fetchConversionJob(jid)
if err != nil {
ers = errorResponse{
Identifier: jid,
Message: "unable to fetch conversion job",
}
requestInternalServerErrorResponse(&w, r, ers)
return
}
if !found {
ers = errorResponse{
Identifier: jid,
Message: "request not found on conversion queue",
}
requestNotFoundResponse(&w, r, ers)
return
}
rrs, err := cj.generateRenderResponse(clt)
if err != nil {
ers = errorResponse{
Identifier: cj.Identifier,
Message: "failed to generate render response",
}
requestInternalServerErrorResponse(&w, r, ers)
return
}
log.WithFields(log.Fields{
"uuid": cj.Identifier,
}).Info("conversion job status check completed")
requestOKResponse(&w, r, rrs)
}
func (cj *ConversionJob) generateRenderResponse(clt *Client) (renderResponse, error) {
rrs := renderResponse{
Identifier: cj.Identifier,
CreatedAt: cj.CreatedAt,
StartedAt: cj.StartedAt,
EndedAt: cj.EndedAt,
ExpiresIn: cj.ExpiresIn,
Status: cj.Status,
}
logs := string(cj.Logs)
logs = strings.TrimSpace(logs)
logs = strings.Replace(logs, "\r", "\n", -1)
rrs.Logs = strings.Split(logs, "\n")
for i, entry := range rrs.Logs {
rrs.Logs[i] = strings.TrimSpace(entry)
}
if cj.Status != "succeeded" {
return rrs, nil
}
log.WithFields(log.Fields{
"uuid": cj.Identifier,
}).Debugln("conversion job found completed")
timeToExpire := 5 * time.Minute
surl, err := clt.getFileS3SignedURL(cj, timeToExpire)
if err != nil {
log.WithFields(log.Fields{
"uuid": cj.Identifier,
}).Error(err)
return rrs, err
}
rrs.FileURL = surl
return rrs, nil
}
// StartServer starts the application web server
func (clt *Client) StartServer() {
requestTTL := viper.GetInt("server.request_ttl")
log.Infof("request TTL set to %d seconds", requestTTL)
health := healthcheck.NewHandler()
redisAddress := viper.GetString("redis.host")
redisPort := viper.GetInt("redis.port")
redisHost := fmt.Sprintf("%s:%d", redisAddress, redisPort)
redisTCPCheck := healthcheck.TCPDialCheck(redisHost, 50*time.Millisecond)
health.AddReadinessCheck("redis-tcp-connection", redisTCPCheck)
router := mux.NewRouter()
router.HandleFunc("/health/live", health.LiveEndpoint).
Methods("GET")
router.HandleFunc("/health/ready", health.ReadyEndpoint).
Methods("GET")
router.HandleFunc("/render/{target}", clt.renderHandler).
Headers("Content-Type", "application/json").
Methods("POST")
router.HandleFunc("/status/{uuid}", clt.statusHandler).
Headers("Content-Type", "application/json").
Methods("GET")
bindingAddress := viper.GetString("server.binding_address")
bindingPort := viper.GetInt("server.binding_port")
binding := fmt.Sprintf("%s:%d", bindingAddress, bindingPort)
log.Infof("listening on http://%s", binding)
http.Handle("/", router)
http.ListenAndServe(binding, nil)
}