~evanj/cms

ref: 977e0de28ca8f9d30d073665642e89fddfde493f cms/cms.go -rw-r--r-- 2.3 KiB
977e0de2Evan J Feat(cms.go): Retrying if requests last too long. Effective max request 1 year, 19 days ago
                                                                                
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
// cms is a free and open source content management system.
package main

import (
	"bytes"
	"context"
	"log"
	"net/http"
	"strings"
	"time"
)

type App struct {
	log *log.Logger

	// NOTE: Concurrent read (only) is OK. This is never wrote (but defined on
	// server startup).
	handlers map[string]http.Handler
}

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) < 2 {
		http.NotFound(w, r)
		return
	}

	namespace := parts[1]
	if namespace == "" {
		namespace = "user"
	}

	h, ok := a.handlers[namespace]
	if !ok {
		http.NotFound(w, r)
		return
	}

	a.handleWithRetry(w, r, h)
}

type wrappedResponseWriter struct {
	w  http.ResponseWriter
	h  http.Header
	sc int
	b  bytes.Buffer
}

func (rw *wrappedResponseWriter) Header() http.Header             { return rw.h }
func (rw *wrappedResponseWriter) Write(bytes []byte) (int, error) { return rw.b.Write(bytes) }
func (rw *wrappedResponseWriter) WriteHeader(statusCode int)      { rw.sc = statusCode }

func (rw *wrappedResponseWriter) Flush() error {
	rw.w.WriteHeader(rw.sc)
	_, err := rw.w.Write(rw.b.Bytes())
	return err
}

// handleWithRetry will retry requests when we're approaching long request
// times in an effort to lower tail latency.
func (a *App) handleWithRetry(w http.ResponseWriter, r *http.Request, h http.Handler) {
	var (
		// Effective max request time is 30 seconds (ten seconds will be retried
		// three times).
		maxAttempts = 3
		maxTime     = 10 * time.Second
		err         error
	)

	for i := 0; i < maxAttempts; i++ {
		var (
			ctx, cancel = context.WithTimeout(context.Background(), maxTime)
			wWrap       = &wrappedResponseWriter{w: w, h: http.Header{}, b: bytes.Buffer{}}
			successCh   = handle(wWrap, r.WithContext(ctx), h)
		)
		defer cancel()

		select {
		case <-ctx.Done():
			err = ctx.Err()
		case <-successCh:
			if err := wWrap.Flush(); err != nil {
				// TODO: Is there a more appropriate way to handle an error here?...
				a.log.Println(err)
			}
			return
		}
	}

	// TODO: Probably want a better error message.
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte(err.Error()))
}

func handle(w http.ResponseWriter, r *http.Request, h http.Handler) chan struct{} {
	c := make(chan struct{})

	go func(c chan struct{}) {
		h.ServeHTTP(w, r)
		c <- struct{}{}
	}(c)

	return c
}