This repository has been archived by the owner on Apr 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcache.go
238 lines (207 loc) · 5.21 KB
/
cache.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
package httpcache
import (
"bufio"
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/textproto"
"os"
pathutil "path"
"strconv"
"strings"
"time"
"github.com/rainycape/vfs"
)
const (
headerPrefix = "header/"
bodyPrefix = "body/"
formatPrefix = "v1/"
)
// Returned when a resource doesn't exist
var ErrNotFoundInCache = errors.New("Not found in cache")
type Cache interface {
Header(key string) (Header, error)
Store(res *Resource, keys ...string) error
Retrieve(key string) (*Resource, error)
Invalidate(keys ...string)
Freshen(res *Resource, keys ...string) error
}
// cache provides a storage mechanism for cached Resources
type cache struct {
fs vfs.VFS
stale map[string]time.Time
}
var _ Cache = (*cache)(nil)
type Header struct {
http.Header
StatusCode int
}
// NewCache returns a cache backend off the provided VFS
func NewVFSCache(fs vfs.VFS) Cache {
return &cache{fs: fs, stale: map[string]time.Time{}}
}
// NewMemoryCache returns an ephemeral cache in memory
func NewMemoryCache() Cache {
return NewVFSCache(vfs.Memory())
}
// NewDiskCache returns a disk-backed cache
func NewDiskCache(dir string) (Cache, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
fs, err := vfs.FS(dir)
if err != nil {
return nil, err
}
chfs, err := vfs.Chroot("/", fs)
if err != nil {
return nil, err
}
return NewVFSCache(chfs), nil
}
func (c *cache) vfsWrite(path string, r io.Reader) error {
if err := vfs.MkdirAll(c.fs, pathutil.Dir(path), 0700); err != nil {
return err
}
f, err := c.fs.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, r); err != nil {
return err
}
return nil
}
// Retrieve the Status and Headers for a given key path
func (c *cache) Header(key string) (Header, error) {
path := headerPrefix + formatPrefix + hashKey(key)
f, err := c.fs.Open(path)
if err != nil {
if vfs.IsNotExist(err) {
return Header{}, ErrNotFoundInCache
}
return Header{}, err
}
return readHeaders(bufio.NewReader(f))
}
// Store a resource against a number of keys
func (c *cache) Store(res *Resource, keys ...string) error {
var buf = &bytes.Buffer{}
if length, err := strconv.ParseInt(res.Header().Get("Content-Length"), 10, 64); err == nil {
if _, err = io.CopyN(buf, res, length); err != nil {
return err
}
} else if _, err = io.Copy(buf, res); err != nil {
return err
}
for _, key := range keys {
delete(c.stale, key)
if err := c.storeBody(buf, key); err != nil {
return err
}
if err := c.storeHeader(res.Status(), res.Header(), key); err != nil {
return err
}
}
return nil
}
func (c *cache) storeBody(r io.Reader, key string) error {
if err := c.vfsWrite(bodyPrefix+formatPrefix+hashKey(key), r); err != nil {
return err
}
return nil
}
func (c *cache) storeHeader(code int, h http.Header, key string) error {
hb := &bytes.Buffer{}
hb.Write([]byte(fmt.Sprintf("HTTP/1.1 %d %s\r\n", code, http.StatusText(code))))
headersToWriter(h, hb)
if err := c.vfsWrite(headerPrefix+formatPrefix+hashKey(key), bytes.NewReader(hb.Bytes())); err != nil {
return err
}
return nil
}
// Retrieve returns a cached Resource for the given key
func (c *cache) Retrieve(key string) (*Resource, error) {
f, err := c.fs.Open(bodyPrefix + formatPrefix + hashKey(key))
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
h, err := c.Header(key)
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
res := NewResource(h.StatusCode, f, h.Header)
if staleTime, exists := c.stale[key]; exists {
if !res.DateAfter(staleTime) {
log.Printf("stale marker of %s found", staleTime)
res.MarkStale()
}
}
return res, nil
}
func (c *cache) Invalidate(keys ...string) {
log.Printf("invalidating %q", keys)
for _, key := range keys {
c.stale[key] = Clock()
}
}
func (c *cache) Freshen(res *Resource, keys ...string) error {
for _, key := range keys {
if h, err := c.Header(key); err == nil {
if h.StatusCode == res.Status() && headersEqual(h.Header, res.Header()) {
debugf("freshening key %s", key)
if err := c.storeHeader(h.StatusCode, res.Header(), key); err != nil {
return err
}
} else {
debugf("freshen failed, invalidating %s", key)
c.Invalidate(key)
}
}
}
return nil
}
func hashKey(key string) string {
h := sha256.New()
io.WriteString(h, key)
return fmt.Sprintf("%x", h.Sum(nil))
}
func readHeaders(r *bufio.Reader) (Header, error) {
tp := textproto.NewReader(r)
line, err := tp.ReadLine()
if err != nil {
return Header{}, err
}
f := strings.SplitN(line, " ", 3)
if len(f) < 2 {
return Header{}, fmt.Errorf("malformed HTTP response: %s", line)
}
statusCode, err := strconv.Atoi(f[1])
if err != nil {
return Header{}, fmt.Errorf("malformed HTTP status code: %s", f[1])
}
mimeHeader, err := tp.ReadMIMEHeader()
if err != nil {
return Header{}, err
}
return Header{StatusCode: statusCode, Header: http.Header(mimeHeader)}, nil
}
func headersToWriter(h http.Header, w io.Writer) error {
if err := h.Write(w); err != nil {
return err
}
// ReadMIMEHeader expects a trailing newline
_, err := w.Write([]byte("\r\n"))
return err
}