-
Notifications
You must be signed in to change notification settings - Fork 258
/
io.go
179 lines (142 loc) · 3.98 KB
/
io.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
package main
import (
"errors"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/contentsquare/chproxy/cache"
"github.com/contentsquare/chproxy/log"
"github.com/prometheus/client_golang/prometheus"
)
type ResponseWriterWithCode interface {
http.ResponseWriter
StatusCode() int
}
type StatResponseWriter interface {
http.ResponseWriter
http.CloseNotifier
StatusCode() int
SetStatusCode(code int)
}
var _ StatResponseWriter = &statResponseWriter{}
// statResponseWriter collects the amount of bytes written.
//
// The wrapped ResponseWriter must implement http.CloseNotifier.
//
// Additionally it caches response status code.
type statResponseWriter struct {
http.ResponseWriter
statusCode int
// wroteHeader tells whether the header's been written to
// the original ResponseWriter
wroteHeader bool
bytesWritten prometheus.Counter
}
const (
XCacheHit = "HIT"
XCacheMiss = "MISS"
XCacheNA = "N/A"
)
func RespondWithData(rw http.ResponseWriter, data io.Reader, metadata cache.ContentMetadata, ttl time.Duration, cacheHit string, statusCode int, labels prometheus.Labels) error {
h := rw.Header()
if len(metadata.Type) > 0 {
h.Set("Content-Type", metadata.Type)
}
if len(metadata.Encoding) > 0 {
h.Set("Content-Encoding", metadata.Encoding)
}
h.Set("Content-Length", fmt.Sprintf("%d", metadata.Length))
if ttl > 0 {
expireSeconds := uint(ttl / time.Second)
h.Set("Cache-Control", fmt.Sprintf("max-age=%d", expireSeconds))
}
h.Set("X-Cache", cacheHit)
rw.WriteHeader(statusCode)
if _, err := io.Copy(rw, data); err != nil {
var perr *cache.RedisCacheError
if errors.As(err, &perr) {
cacheCorruptedFetch.With(labels).Inc()
log.Debugf("redis cache error")
}
log.Errorf("cannot send response to client: %s", err)
return fmt.Errorf("cannot send response to client: %w", err)
}
return nil
}
func (rw *statResponseWriter) SetStatusCode(code int) {
rw.statusCode = code
}
func (rw *statResponseWriter) StatusCode() int {
if rw.statusCode == 0 {
return http.StatusOK
}
return rw.statusCode
}
func (rw *statResponseWriter) Write(b []byte) (int, error) {
if rw.statusCode == 0 {
rw.statusCode = http.StatusOK
}
if !rw.wroteHeader {
rw.ResponseWriter.WriteHeader(rw.statusCode)
rw.wroteHeader = true
}
n, err := rw.ResponseWriter.Write(b)
rw.bytesWritten.Add(float64(n))
return n, err
}
func (rw *statResponseWriter) WriteHeader(statusCode int) {
// cache statusCode to keep the opportunity to change it in further
rw.statusCode = statusCode
}
// CloseNotify implements http.CloseNotifier
func (rw *statResponseWriter) CloseNotify() <-chan bool {
// The rw.ResponseWriter must implement http.CloseNotifier
rwc, ok := rw.ResponseWriter.(http.CloseNotifier)
if !ok {
panic("BUG: the wrapped ResponseWriter must implement http.CloseNotifier")
}
return rwc.CloseNotify()
}
var _ io.ReadCloser = &statReadCloser{}
// statReadCloser collects the amount of bytes read.
type statReadCloser struct {
io.ReadCloser
bytesRead prometheus.Counter
}
func (src *statReadCloser) Read(p []byte) (int, error) {
n, err := src.ReadCloser.Read(p)
src.bytesRead.Add(float64(n))
return n, err
}
var _ io.ReadCloser = &cachedReadCloser{}
// cachedReadCloser caches the first 1Kb form the wrapped ReadCloser.
type cachedReadCloser struct {
io.ReadCloser
// bLock protects b from concurrent access when Read and String
// are called from concurrent goroutines.
bLock sync.Mutex
// b holds up to 1Kb of the initial data read from ReadCloser.
b []byte
}
func (crc *cachedReadCloser) Read(p []byte) (int, error) {
n, err := crc.ReadCloser.Read(p)
crc.bLock.Lock()
if len(crc.b) < 1024 {
crc.b = append(crc.b, p[:n]...)
if len(crc.b) >= 1024 {
crc.b = append(crc.b[:1024], "..."...)
}
}
crc.bLock.Unlock()
// Do not cache the last read operation, since it slows down
// reading large amounts of data such as large INSERT queries.
return n, err
}
func (crc *cachedReadCloser) String() string {
crc.bLock.Lock()
s := string(crc.b)
crc.bLock.Unlock()
return s
}