-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
394 lines (311 loc) · 10.1 KB
/
http.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package handoff
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"regexp"
"strconv"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/raphi011/handoff/internal/html"
"github.com/raphi011/handoff/internal/html/assets"
"github.com/raphi011/handoff/internal/model"
"github.com/yuin/goldmark"
)
type malformedRequestError struct {
param string
reason string
}
func (e malformedRequestError) Error() string {
return "malformed request param: " + e.param + " reason: " + e.reason
}
func (s *Server) runHTTP() error {
router := httprouter.New()
router.Handler("GET", "/metrics", promhttp.Handler())
if s.config.EnablePprof {
router.Handler(http.MethodGet, "/debug/pprof/*item", http.DefaultServeMux)
}
router.GET("/healthz", s.getHealth)
router.GET("/ready", s.getReady)
router.POST("/suites/:suite-name/runs", s.startTestSuite)
router.GET("/suites", s.getTestSuitesWithRuns)
router.GET("/suites/:suite-name/runs", s.getTestSuiteRuns)
router.GET("/suites/:suite-name/runs/:run-id", s.getTestSuiteRun)
router.GET("/suites/:suite-name/runs/:run-id/test/:test-name", s.getTestRunResult)
router.GET("/schedules", s.getSchedules)
router.POST("/schedules/:schedule-name", s.createSchedule)
router.DELETE("/schedules/:schedule-name", s.deleteSchedule)
router.ServeFiles("/assets/*filepath", http.FS(assets.Assets))
s.httpServer = &http.Server{
Handler: router,
// TODO: set reasonable timeouts
// needed for debug/pprof/profile endpoint
WriteTimeout: 31 * time.Second,
}
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.config.HostIP, s.config.Port))
if err != nil {
return fmt.Errorf("listening on port %d: %w", s.config.Port, err)
}
if s.config.Port == 0 {
// if we are using a randomly assigned port put it back into the config
// so that e.g. tests know where to send requests to.
s.config.Port = l.Addr().(*net.TCPAddr).Port
}
s.log.Info("Starting http server", "host", s.config.HostIP, "port", s.config.Port)
go func() {
err = s.httpServer.Serve(l)
if err != nil && err != http.ErrServerClosed {
s.log.Error("http server failed", "error", err)
}
}()
return nil
}
func (s *Server) stopHTTP() chan error {
httpStopped := make(chan error)
go func() {
timeoutCtx, cancelTimeout := context.WithTimeout(context.Background(), time.Second*30)
defer cancelTimeout()
err := s.httpServer.Shutdown(timeoutCtx)
httpStopped <- err
}()
return httpStopped
}
func (s *Server) startTestSuite(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ts, err := s.loadTestSuite(r, p)
if err != nil {
s.httpError(w, err)
return
}
reference := r.URL.Query().Get("ref")
initiatedBy := r.URL.Query().Get("initiatedby")
idempotencyKey := r.Header.Get("Idempotency-Key")
filter, err := filterParam(ts, r)
if err != nil {
s.httpError(w, err)
return
}
tsr, err := s.startNewTestSuiteRun(ts, model.RunParams{
InitiatedBy: initiatedBy,
TestFilter: filter,
Reference: reference,
IdempotencyKey: idempotencyKey,
})
if err != nil {
s.httpError(w, err)
}
s.writeResponse(w, r, http.StatusCreated, tsr)
}
func (s *Server) getSchedules(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var schedules []model.ScheduledRun
schedules = append(schedules, s.readOnlySchedules...)
s.writeResponse(w, r, http.StatusOK, schedules)
}
func (s *Server) deleteSchedule(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
scheduleName := p.ByName("schedule-name")
if scheduleName == "" {
s.httpError(w, malformedRequestError{":schedule-name", "must provide a schedule name to delete"})
return
}
err := s.storage.DeleteScheduledRun(context.Background(), scheduleName)
if err != nil {
s.httpError(w, fmt.Errorf("failed to delete scheduled run: %w", err))
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) createSchedule(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
scheduleName := p.ByName("schedule-name")
ts, err := s.loadTestSuite(r, p)
if err != nil {
s.httpError(w, err)
return
}
schedule := r.Header.Get("schedule")
filter, err := filterParam(ts, r)
if err != nil {
s.httpError(w, err)
return
}
sr := model.ScheduledRun{
Name: scheduleName,
TestSuiteName: ts.Name,
Schedule: schedule,
TestFilter: filter,
}
if _, err := s.startSchedule(sr, true); err != nil {
s.httpError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
}
func filterParam(ts model.TestSuite, r *http.Request) (*regexp.Regexp, error) {
filter := r.URL.Query().Get("filter")
if filter == "" {
return nil, nil
}
filterRegex, err := regexp.Compile(filter)
if err != nil {
return nil, malformedRequestError{param: "filter", reason: "invalid regex"}
}
if len(ts.FilterTests(filterRegex)) == 0 {
return nil, malformedRequestError{param: "filter", reason: "no tests match the given filter"}
}
return filterRegex, nil
}
func (s *Server) getTestSuites(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
testSuites := make([]model.TestSuite, len(s.readOnlyTestSuites))
i := 0
for _, ts := range s.readOnlyTestSuites {
testSuites[i] = ts
i++
}
s.writeResponse(w, r, http.StatusOK, testSuites)
}
func (s *Server) getTestSuitesWithRuns(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
testSuitesWitRuns := make([]model.TestSuiteWithRuns, 0, len(s.readOnlyTestSuites))
for _, suite := range s.readOnlyTestSuites {
runs, err := s.storage.LoadTestSuiteRunsByName(r.Context(), suite.Name)
if err != nil {
s.httpError(w, err)
return
}
testSuitesWitRuns = append(testSuitesWitRuns, model.TestSuiteWithRuns{
Suite: suite,
SuiteRuns: runs,
})
}
s.writeResponse(w, r, http.StatusOK, testSuitesWitRuns)
}
func (s *Server) getTestSuiteRun(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
testRun, err := s.loadTestSuiteRun(r.Context(), p)
if err != nil {
s.httpError(w, err)
return
}
s.writeResponse(w, r, http.StatusOK, testRun)
}
func (s *Server) getTestRunResult(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
testRun, err := s.loadTestRuns(r.Context(), r, p)
if err != nil {
s.httpError(w, err)
return
}
s.writeResponse(w, r, http.StatusOK, testRun)
}
func (s *Server) getHealth(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.WriteHeader(http.StatusOK)
}
func (s *Server) getReady(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.WriteHeader(http.StatusOK)
}
func (s *Server) getTestSuiteRuns(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
testRuns, err := s.loadTestSuiteRuns(r.Context(), p)
if err != nil {
s.httpError(w, err)
return
}
if err := s.writeResponse(w, r, http.StatusOK, testRuns); err != nil {
s.log.Warn("writing get test suite runs response", "error", err)
}
}
func (s *Server) writeResponse(w http.ResponseWriter, r *http.Request, status int, body any) error {
var err error
if headerAcceptsType(r.Header, "text/html") {
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(status)
switch t := body.(type) {
case model.TestRun:
err = html.RenderTestRun(t).Render(r.Context(), w)
case []model.ScheduledRun:
err = html.RenderSchedules(t).Render(r.Context(), w)
case model.TestSuiteRun:
err = html.RenderTestSuiteRun(t).Render(r.Context(), w)
case []model.TestSuiteRun:
var buf bytes.Buffer
if err := goldmark.Convert([]byte(`# Header
*bold* **italic**
`), &buf); err != nil {
panic(err)
}
err = html.RenderTestSuiteRuns(buf.String(), t).Render(r.Context(), w)
case []model.TestSuite:
err = html.RenderTestSuites(t).Render(r.Context(), w)
case []model.TestSuiteWithRuns:
err = html.RenderTestSuitesWithRuns(t).Render(r.Context(), w)
default:
return fmt.Errorf("no template available for type %v", t)
}
} else {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
enc := json.NewEncoder(w)
err = enc.Encode(body)
}
if err != nil {
return fmt.Errorf("marshalling response: %w", err)
}
return nil
}
func headerAcceptsType(h http.Header, mimeType string) bool {
accept := h.Get("Accept")
return strings.Contains(accept, mimeType)
}
func (s *Server) loadTestSuite(_ *http.Request, p httprouter.Params) (model.TestSuite, error) {
suiteName := p.ByName("suite-name")
ts, ok := s.readOnlyTestSuites[suiteName]
if !ok {
return model.TestSuite{}, model.NotFoundError{}
}
return ts, nil
}
func (s *Server) loadTestRuns(ctx context.Context, _ *http.Request, p httprouter.Params) ([]model.TestRun, error) {
suiteName := p.ByName("suite-name")
testName := p.ByName("test-name")
runID, err := strconv.Atoi(p.ByName("run-id"))
if err != nil {
return []model.TestRun{}, malformedRequestError{param: "run-id", reason: "must be an integer"}
}
tsr, err := s.storage.LoadTestSuiteRun(ctx, suiteName, runID)
if err != nil {
return []model.TestRun{}, err
}
tr := tsr.TestRunsByName(testName)
return tr, nil
}
func (s *Server) loadTestSuiteRuns(ctx context.Context, p httprouter.Params) ([]model.TestSuiteRun, error) {
suiteName := p.ByName("suite-name")
return s.storage.LoadTestSuiteRunsByName(ctx, suiteName)
}
func (s *Server) loadTestSuiteRun(ctx context.Context, p httprouter.Params) (model.TestSuiteRun, error) {
suiteName := p.ByName("suite-name")
runID, err := strconv.Atoi(p.ByName("run-id"))
if err != nil {
return model.TestSuiteRun{}, malformedRequestError{param: "run-id", reason: "must be an integer"}
}
tr, err := s.storage.LoadTestSuiteRun(ctx, suiteName, runID)
if err != nil {
return model.TestSuiteRun{}, err
}
return tr, nil
}
func (s *Server) httpError(w http.ResponseWriter, err error) {
var notFound model.NotFoundError
var malformedRequest malformedRequestError
if errors.As(err, ¬Found) {
w.WriteHeader(http.StatusNotFound)
return
} else if errors.As(err, &malformedRequest) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusInternalServerError)
s.log.Warn("internal server error", "error", err)
}