-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathcache.go
More file actions
1157 lines (1033 loc) · 32.1 KB
/
Copy pathcache.go
File metadata and controls
1157 lines (1033 loc) · 32.1 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
Copyright (c) 2018 Victor Springer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package cache
import (
"bytes"
"context"
"crypto/sha256"
"encoding/gob"
"errors"
"fmt"
"hash"
"hash/fnv"
"io"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const cacheStatusCodeHeader = "Http-Cache-Status-Code"
const methodPurge = "PURGE"
// CacheEventType identifies an observed cache middleware event.
type CacheEventType string
const (
// CacheEventHit means a valid cached response was served.
CacheEventHit CacheEventType = "hit"
// CacheEventMiss means no cached response was found.
CacheEventMiss CacheEventType = "miss"
// CacheEventStale means an expired cached response was found and released.
CacheEventStale CacheEventType = "stale"
// CacheEventRefresh means a cached response was explicitly released.
CacheEventRefresh CacheEventType = "refresh"
// CacheEventStore means a response was stored in cache.
CacheEventStore CacheEventType = "store"
// CacheEventPurge means a cached response was explicitly purged.
CacheEventPurge CacheEventType = "purge"
)
// CacheEvent is passed to an observer when cache middleware events happen.
type CacheEvent struct {
Type CacheEventType
Request *http.Request
Key uint64
StatusCode int
}
// Observer receives cache middleware events.
type Observer func(CacheEvent)
// Response is the cached response data structure.
type Response struct {
// Value is the cached response value.
Value []byte
// Header is the cached response header.
Header http.Header
// Expiration is the cached response expiration date.
Expiration time.Time
// LastAccess is the last date a cached response was accessed.
// Used by LRU and MRU algorithms.
LastAccess time.Time
// Frequency is the count of times a cached response is accessed.
// Used for LFU and MFU algorithms.
Frequency int
// CanonicalKey is a fingerprint of the request inputs (URL, vary
// headers and body) that produced this entry. The middleware
// compares it against the incoming request on every hit so an
// FNV-64 collision (or a manually corrupted entry) cannot serve
// one client's response to another. Entries written by older
// versions of this package have an empty CanonicalKey and bypass
// verification for backward compatibility.
CanonicalKey []byte
}
// Client data structure for HTTP cache middleware.
type Client struct {
adapter Adapter
adapterTouch AdapterTouch
ttl time.Duration
ttlSet bool
refreshKey string
methods []string
skipCacheHeader string
skipCachePathRegex *regexp.Regexp
varyHeaders []string
statusCodeFilter func(int) bool
writeExpiresHeader bool
observer Observer
purgeEnabled bool
maxBodySize int
singleflightEnabled bool
respectCacheControl bool
staleWindow time.Duration
sf singleflightGroup
}
// ClientOption is used to set Client settings.
type ClientOption func(c *Client) error
// Adapter interface for HTTP cache middleware client.
type Adapter interface {
// Get retrieves the cached response by a given key. It also
// returns true or false, whether it exists or not.
Get(key uint64) ([]byte, bool)
// Set caches a response for a given key until an expiration date.
Set(key uint64, response []byte, expiration time.Time)
// Release frees cache for a given key.
Release(key uint64)
}
// AdapterTouch is an optional Adapter extension. When an adapter
// implements it, the middleware records each cache hit via Touch
// instead of re-encoding the response and calling Set, eliminating the
// read-modify-write lost-update race and the per-hit gob round-trip.
// Adapters that do not implement Touch keep receiving the legacy Set
// call so existing custom adapters retain their behavior.
type AdapterTouch interface {
Touch(key uint64)
}
// Middleware is the HTTP cache middleware handler.
func (c *Client) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if c.purgeEnabled && r.Method == methodPurge && c.cacheableURIPath(r.URL) {
key, _, err := c.key(r)
if err != nil {
next.ServeHTTP(w, r)
return
}
c.adapter.Release(key)
c.observe(CacheEventPurge, r, key, http.StatusNoContent)
w.WriteHeader(http.StatusNoContent)
return
}
if c.cacheableMethod(r.Method) && c.cacheableURIPath(r.URL) {
// Honor request-side Cache-Control when opted in. no-store
// short-circuits both the lookup and the store paths; no-cache
// only skips the lookup so the handler runs against the
// origin while the response can still be stored.
var reqCC cacheControl
if c.respectCacheControl {
reqCC = parseCacheControl(r.Header.Get("Cache-Control"))
if reqCC.noStore {
next.ServeHTTP(w, r)
return
}
}
key, fingerprint, err := c.key(r)
if err != nil {
next.ServeHTTP(w, r)
return
}
// Refresh detection is opt-in via ClientWithRefreshKey; an empty
// refreshKey would otherwise match URLs containing a bare "?=x"
// (empty query key, non-empty value) and let any caller wipe the
// cache entry.
refreshed := false
if c.refreshKey != "" {
params := r.URL.Query()
if _, ok := params[c.refreshKey]; ok {
delete(params, c.refreshKey)
r.URL.RawQuery = params.Encode()
key, fingerprint, err = c.key(r)
if err != nil {
next.ServeHTTP(w, r)
return
}
c.adapter.Release(key)
c.observe(CacheEventRefresh, r, key, 0)
refreshed = true
}
}
if !refreshed && !reqCC.noCache {
b, ok := c.adapter.Get(key)
switch {
case !ok:
c.observe(CacheEventMiss, r, key, 0)
default:
response, decodeErr := decodeResponse(b)
switch {
case decodeErr != nil:
// Corrupted or version-skewed entry: drop it and
// fall through to the origin as a miss.
c.adapter.Release(key)
c.observe(CacheEventMiss, r, key, 0)
case !canonicalKeyMatches(response.CanonicalKey, fingerprint):
// FNV-64 collision (or corrupted entry from a
// different logical request): release the stored
// blob and serve a fresh response.
c.adapter.Release(key)
c.observe(CacheEventMiss, r, key, 0)
case response.Valid():
if c.adapterTouch != nil {
c.adapterTouch.Touch(key)
} else {
// Legacy in-blob bookkeeping for adapters that
// don't implement AdapterTouch. Subject to the
// lost-update race under concurrency, but
// preserved for backward compatibility.
response.LastAccess = time.Now()
response.Frequency++
c.adapter.Set(key, response.Bytes(), response.Expiration)
}
statusCode := cachedStatusCode(response.Header)
c.observe(CacheEventHit, r, key, statusCode)
// Skip the wire writes for clients that already
// disconnected. cachedStatusCode never returns 0
// (it normalizes to http.StatusOK), so an
// unconditional WriteHeader is safe.
if r.Context().Err() != nil {
return
}
writeHeader(w.Header(), response.Header)
if c.writeExpiresHeader && !response.Expiration.IsZero() {
w.Header().Set("Expires", response.Expiration.UTC().Format(http.TimeFormat))
}
w.WriteHeader(statusCode)
w.Write(response.Value)
return
default:
if c.staleWindow > 0 && time.Since(response.Expiration) <= c.staleWindow {
// Within RFC 5861 stale-while-revalidate
// window: serve stale immediately and
// refresh the entry in the background.
statusCode := cachedStatusCode(response.Header)
c.observe(CacheEventHit, r, key, statusCode)
c.scheduleRefresh(r, next, key, fingerprint)
if r.Context().Err() != nil {
return
}
writeHeader(w.Header(), response.Header)
if c.writeExpiresHeader && !response.Expiration.IsZero() {
w.Header().Set("Expires", response.Expiration.UTC().Format(http.TimeFormat))
}
w.WriteHeader(statusCode)
w.Write(response.Value)
return
}
c.adapter.Release(key)
c.observe(CacheEventStale, r, key, 0)
}
}
}
if c.singleflightEnabled {
payload, _ := c.sf.Do(strconv.FormatUint(key, 36), func() interface{} {
cw := newCaptureWriter(c.maxBodySize)
next.ServeHTTP(cw, r)
statusCode := cw.statusCodeValue()
if c.cacheableSnapshot(cw.header, cw.wrote, cw.exceeded, statusCode) {
now := time.Now()
ttl := c.responseTTL(cw.header)
expires := time.Time{}
if ttl > 0 {
expires = now.Add(ttl)
}
response := Response{
Value: cw.body.Bytes(),
Header: cacheHeader(cw.header, statusCode),
Expiration: expires,
LastAccess: now,
Frequency: 1,
CanonicalKey: fingerprint,
}
c.adapter.Set(key, response.Bytes(), response.Expiration)
c.observe(CacheEventStore, r, key, statusCode)
}
return cw
})
cw := payload.(*captureWriter)
writeCapturedResponse(w, cw)
return
}
rw := newResponseWriter(w, c.maxBodySize)
next.ServeHTTP(rw, r)
statusCode := rw.statusCodeValue()
value := rw.body.Bytes()
now := time.Now()
ttl := c.responseTTL(rw.Header())
expires := time.Time{}
if ttl > 0 {
expires = now.Add(ttl)
}
if c.cacheableResponse(rw, statusCode) {
response := Response{
Value: value,
Header: cacheHeader(rw.Header(), statusCode),
Expiration: expires,
LastAccess: now,
Frequency: 1,
CanonicalKey: fingerprint,
}
c.adapter.Set(key, response.Bytes(), response.Expiration)
c.observe(CacheEventStore, r, key, statusCode)
}
return
}
next.ServeHTTP(w, r)
})
}
// scheduleRefresh kicks off a background revalidation of a stale entry.
// The work is coalesced through the same singleflight group used by
// ClientWithSingleflight, so a stampede of concurrent stale hits runs
// exactly one origin request. The refresh outlives the caller's
// context: it is given context.Background() so a disconnect on the
// triggering request does not abort the refill.
func (c *Client) scheduleRefresh(r *http.Request, next http.Handler, key uint64, fingerprint []byte) {
cloned := r.Clone(context.Background())
go c.sf.Do(strconv.FormatUint(key, 36), func() interface{} {
if b, ok := c.adapter.Get(key); ok {
if resp, err := decodeResponse(b); err == nil && resp.Valid() {
return nil
}
}
cw := newCaptureWriter(c.maxBodySize)
next.ServeHTTP(cw, cloned)
statusCode := cw.statusCodeValue()
if !c.cacheableSnapshot(cw.header, cw.wrote, cw.exceeded, statusCode) {
return nil
}
now := time.Now()
ttl := c.responseTTL(cw.header)
expires := time.Time{}
if ttl > 0 {
expires = now.Add(ttl)
}
response := Response{
Value: cw.body.Bytes(),
Header: cacheHeader(cw.header, statusCode),
Expiration: expires,
LastAccess: now,
Frequency: 1,
CanonicalKey: fingerprint,
}
c.adapter.Set(key, response.Bytes(), response.Expiration)
c.observe(CacheEventStore, cloned, key, statusCode)
return nil
})
}
// Drop releases the cache entry matching the given request. The caller's
// *http.Request is left unmodified: its URL.RawQuery is not reordered
// and its Body remains readable after the call returns.
func (c *Client) Drop(r *http.Request) error {
// Read the body up front so the caller gets a fresh reader and we
// can hand a separate, equivalent copy to c.key.
var bodyBytes []byte
if r.Body != nil {
b, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
bodyBytes = b
r.Body = io.NopCloser(bytes.NewBuffer(b))
}
cloned := *r
if r.URL != nil {
u := *r.URL
cloned.URL = &u
}
if bodyBytes != nil {
cloned.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
key, _, err := c.key(&cloned)
if err != nil {
return err
}
c.adapter.Release(key)
return nil
}
func (c *Client) cacheableResponse(rw *responseWriter, statusCode int) bool {
return c.cacheableSnapshot(rw.Header(), rw.wrote, rw.exceeded, statusCode)
}
func (c *Client) cacheableSnapshot(header http.Header, wrote, exceeded bool, statusCode int) bool {
if !wrote {
// Handlers that return without calling Write or WriteHeader
// (early error returns, hijacked connections, abandoned RPCs)
// would otherwise be cached as an empty 200 OK response and
// served back to every subsequent request.
return false
}
if exceeded {
return false
}
if !c.statusCodeFilter(statusCode) {
return false
}
if c.respectCacheControl {
cc := parseCacheControl(header.Get("Cache-Control"))
if cc.noStore || cc.noCache || cc.private {
return false
}
}
if c.skipCacheHeader == "" {
return true
}
return header.Get(c.skipCacheHeader) == ""
}
// responseTTL returns the duration the middleware should keep this
// response cached. When ClientWithRespectCacheControl is enabled the
// response's s-maxage / max-age override the client default.
func (c *Client) responseTTL(header http.Header) time.Duration {
if c.respectCacheControl {
cc := parseCacheControl(header.Get("Cache-Control"))
if cc.hasSMaxAge {
return cc.sMaxAge
}
if cc.hasMaxAge {
return cc.maxAge
}
}
return c.ttl
}
// cacheControl is a tiny subset of RFC 7234 directives recognized by
// ClientWithRespectCacheControl. Unknown directives are intentionally
// ignored so this stays a behavior-preserving opt-in.
type cacheControl struct {
noStore bool
noCache bool
private bool
maxAge time.Duration
hasMaxAge bool
sMaxAge time.Duration
hasSMaxAge bool
}
func parseCacheControl(h string) cacheControl {
var cc cacheControl
if h == "" {
return cc
}
for _, raw := range strings.Split(h, ",") {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
name, value, _ := strings.Cut(raw, "=")
name = strings.ToLower(strings.TrimSpace(name))
value = strings.TrimSpace(value)
if len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' {
value = value[1 : len(value)-1]
}
switch name {
case "no-store":
cc.noStore = true
case "no-cache":
cc.noCache = true
case "private":
cc.private = true
case "max-age":
if n, err := strconv.Atoi(value); err == nil && n >= 0 {
cc.maxAge = time.Duration(n) * time.Second
cc.hasMaxAge = true
}
case "s-maxage":
if n, err := strconv.Atoi(value); err == nil && n >= 0 {
cc.sMaxAge = time.Duration(n) * time.Second
cc.hasSMaxAge = true
}
}
}
return cc
}
func (c *Client) cacheableMethod(method string) bool {
for _, m := range c.methods {
if method == m {
return true
}
}
return false
}
func (c *Client) cacheableURIPath(URL *url.URL) bool {
if c.skipCachePathRegex == nil {
return true
}
return !c.skipCachePathRegex.MatchString(URL.Path)
}
func (c *Client) key(r *http.Request) (uint64, []byte, error) {
sortURLParams(r.URL)
// POST keys include the body. PURGE has to mirror that so it can
// invalidate a cached POST entry; without this, PURGE would always
// compute the body-less key and silently fail to find anything
// stored under URL+body.
bodyKeyed := r.Body != nil &&
(r.Method == http.MethodPost || r.Method == methodPurge)
if !bodyKeyed {
urlStr := r.URL.String()
return generateKeyWithHeaders(urlStr, r.Header, c.varyHeaders),
canonicalFingerprint(urlStr, nil, r.Header, c.varyHeaders),
nil
}
body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return 0, nil, err
}
r.Body = io.NopCloser(bytes.NewBuffer(body))
urlStr := r.URL.String()
return generateKeyWithBodyAndHeaders(urlStr, body, r.Header, c.varyHeaders),
canonicalFingerprint(urlStr, body, r.Header, c.varyHeaders),
nil
}
// canonicalKeyMatches returns true when the stored canonical key matches
// the incoming request's fingerprint. An empty stored key (entries
// written by older versions of this package) bypasses verification to
// preserve backward compatibility with persistent caches.
func canonicalKeyMatches(stored, fingerprint []byte) bool {
if len(stored) == 0 {
return true
}
return bytes.Equal(stored, fingerprint)
}
// sha256Pool reuses hash.Hash instances across canonicalFingerprint
// calls. The hasher's internal state is reset before use, so the only
// state carried across calls is the ~250 bytes of internal buffers that
// would otherwise be allocated per request.
var sha256Pool = sync.Pool{
New: func() interface{} { return sha256.New() },
}
// canonicalFingerprint hashes the request inputs that go into the cache
// key with SHA-256. The middleware stores the fingerprint with each
// cached response and verifies it on every hit so an FNV-64 collision
// cannot serve one request's response to another.
func canonicalFingerprint(URL string, body []byte, headers http.Header, varyHeaders []string) []byte {
h := sha256Pool.Get().(hash.Hash)
h.Reset()
defer sha256Pool.Put(h)
h.Write([]byte(URL))
for _, name := range varyHeaders {
canonName := http.CanonicalHeaderKey(name)
h.Write([]byte{0})
h.Write([]byte(canonName))
for _, v := range headers.Values(canonName) {
h.Write([]byte{0})
h.Write([]byte(v))
}
}
if len(body) > 0 {
h.Write([]byte{0})
h.Write(body)
}
return h.Sum(nil)
}
func (c *Client) observe(eventType CacheEventType, r *http.Request, key uint64, statusCode int) {
if c.observer == nil {
return
}
c.observer(CacheEvent{
Type: eventType,
Request: r,
Key: key,
StatusCode: statusCode,
})
}
func cacheHeader(header http.Header, statusCode int) http.Header {
cachedHeader := cloneHeader(header)
cachedHeader.Del(cacheStatusCodeHeader)
if statusCode != http.StatusOK {
cachedHeader.Set(cacheStatusCodeHeader, strconv.Itoa(statusCode))
}
return cachedHeader
}
func cachedStatusCode(header http.Header) int {
statusCode := header.Get(cacheStatusCodeHeader)
if statusCode == "" {
return http.StatusOK
}
code, err := strconv.Atoi(statusCode)
if err != nil || code < 100 {
return http.StatusOK
}
return code
}
func cloneHeader(header http.Header) http.Header {
cloned := make(http.Header, len(header))
for k, values := range header {
cloned[k] = append([]string(nil), values...)
}
return cloned
}
func writeHeader(dst http.Header, src http.Header) {
for k, values := range src {
if k == cacheStatusCodeHeader {
continue
}
// Use a fresh slice per key. Set-Cookie and other multi-valued
// headers MUST be emitted as separate values; joining them with a
// comma corrupts cookies whose Expires attribute contains a comma.
dst[k] = append([]string(nil), values...)
}
}
// BytesToResponse converts bytes array into Response data structure.
// Decoding errors are silently swallowed for backward compatibility;
// the middleware uses decodeResponse internally so it can detect
// corruption and treat the entry as a cache miss.
func BytesToResponse(b []byte) Response {
r, _ := decodeResponse(b)
return r
}
// decodeResponse returns a Response and any error from the gob decoder
// so callers can distinguish empty/corrupt entries from zero-valued ones.
func decodeResponse(b []byte) (Response, error) {
var r Response
if len(b) == 0 {
return r, errors.New("cache: empty response payload")
}
dec := gob.NewDecoder(bytes.NewReader(b))
if err := dec.Decode(&r); err != nil {
return Response{}, err
}
return r, nil
}
// Valid returns whether the response can still be served from cache.
func (r Response) Valid() bool {
return r.Expiration.IsZero() || r.Expiration.After(time.Now())
}
// Bytes converts Response data structure into bytes array.
func (r Response) Bytes() []byte {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
enc.Encode(&r)
return b.Bytes()
}
func sortURLParams(URL *url.URL) {
params := URL.Query()
for _, param := range params {
sort.Slice(param, func(i, j int) bool {
return param[i] < param[j]
})
}
URL.RawQuery = params.Encode()
}
// KeyAsString can be used by adapters to convert the cache key from uint64 to string.
func KeyAsString(key uint64) string {
return strconv.FormatUint(key, 36)
}
func generateKey(URL string) uint64 {
hash := fnv.New64a()
hash.Write([]byte(URL))
return hash.Sum64()
}
func generateKeyWithBody(URL string, body []byte) uint64 {
hash := fnv.New64a()
hash.Write([]byte(URL))
hash.Write(body)
return hash.Sum64()
}
func generateKeyWithHeaders(URL string, headers http.Header, varyHeaders []string) uint64 {
if len(varyHeaders) == 0 {
return generateKey(URL)
}
hash := fnv.New64a()
writeKeyPart(hash, URL)
writeHeaders(hash, headers, varyHeaders)
return hash.Sum64()
}
func generateKeyWithBodyAndHeaders(URL string, body []byte, headers http.Header, varyHeaders []string) uint64 {
if len(varyHeaders) == 0 {
return generateKeyWithBody(URL, body)
}
hash := fnv.New64a()
writeKeyPart(hash, URL)
writeHeaders(hash, headers, varyHeaders)
hash.Write(body)
return hash.Sum64()
}
func writeHeaders(hash hash.Hash64, headers http.Header, varyHeaders []string) {
for _, header := range varyHeaders {
name := http.CanonicalHeaderKey(header)
writeKeyPart(hash, name)
for _, value := range headers.Values(name) {
writeKeyPart(hash, value)
}
}
}
func writeKeyPart(hash hash.Hash64, value string) {
hash.Write([]byte{0})
hash.Write([]byte(value))
}
// NewClient initializes the cache HTTP middleware client with the given
// options.
func NewClient(opts ...ClientOption) (*Client, error) {
c := &Client{}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
if c.adapter == nil {
return nil, errors.New("cache client adapter is not set")
}
if !c.ttlSet {
return nil, errors.New("cache client ttl is not set")
}
if c.methods == nil {
c.methods = []string{http.MethodGet}
}
if c.statusCodeFilter == nil {
c.statusCodeFilter = func(statusCode int) bool {
return statusCode < 400
}
}
return c, nil
}
// ClientWithAdapter sets the adapter type for the HTTP cache
// middleware client.
func ClientWithAdapter(a Adapter) ClientOption {
return func(c *Client) error {
c.adapter = a
if t, ok := a.(AdapterTouch); ok {
c.adapterTouch = t
} else {
c.adapterTouch = nil
}
return nil
}
}
// ClientWithTTL sets how long each response is going to be cached.
func ClientWithTTL(ttl time.Duration) ClientOption {
return func(c *Client) error {
if int64(ttl) < 0 {
return fmt.Errorf("cache client ttl %v is invalid", ttl)
}
c.ttl = ttl
c.ttlSet = true
return nil
}
}
// ClientWithRefreshKey sets the parameter key used to free a request
// cached response. Optional setting.
func ClientWithRefreshKey(refreshKey string) ClientOption {
return func(c *Client) error {
c.refreshKey = refreshKey
return nil
}
}
// ClientWithMethods sets the acceptable HTTP methods to be cached.
// Optional setting. If not set, default is "GET".
func ClientWithMethods(methods []string) ClientOption {
return func(c *Client) error {
for _, method := range methods {
if method != http.MethodGet && method != http.MethodPost {
return fmt.Errorf("invalid method %s", method)
}
}
c.methods = methods
return nil
}
}
// ClientWithStatusCodeFilter sets the response status codes that can be cached.
// Optional setting. If not set, responses below 400 are cached.
func ClientWithStatusCodeFilter(filter func(int) bool) ClientOption {
return func(c *Client) error {
if filter == nil {
return errors.New("cache client status code filter is not set")
}
c.statusCodeFilter = filter
return nil
}
}
// ClientWithSkipCacheResponseHeader sets a response header that prevents
// successful responses from being stored.
func ClientWithSkipCacheResponseHeader(header string) ClientOption {
return func(c *Client) error {
c.skipCacheHeader = header
return nil
}
}
// ClientWithSkipCacheURIPathRegex skips cache lookup and storage for matching
// request URL paths.
func ClientWithSkipCacheURIPathRegex(pathRegex *regexp.Regexp) ClientOption {
return func(c *Client) error {
c.skipCachePathRegex = pathRegex
return nil
}
}
// ClientWithVaryHeaders includes selected request headers in cache keys.
func ClientWithVaryHeaders(headers []string) ClientOption {
return func(c *Client) error {
c.varyHeaders = headers
return nil
}
}
// ClientWithExpiresHeader enables middleware to add an Expires header to responses.
// Optional setting. If not set, default is false.
func ClientWithExpiresHeader() ClientOption {
return func(c *Client) error {
c.writeExpiresHeader = true
return nil
}
}
// ClientWithObserver sets a function that receives cache middleware events.
// Optional setting.
func ClientWithObserver(observer Observer) ClientOption {
return func(c *Client) error {
if observer == nil {
return errors.New("cache client observer is not set")
}
c.observer = observer
return nil
}
}
// ClientWithPurge enables handling PURGE requests by releasing matching cache entries.
// Optional setting.
func ClientWithPurge() ClientOption {
return func(c *Client) error {
c.purgeEnabled = true
return nil
}
}
// ClientWithSingleflight coalesces concurrent cache misses for the same
// key so the origin handler runs only once per cache-miss batch. All
// concurrent callers receive the same response. Defaults off so callers
// who depend on per-request handler invocations are not surprised.
func ClientWithSingleflight() ClientOption {
return func(c *Client) error {
c.singleflightEnabled = true
return nil
}
}
// ClientWithStaleWhileRevalidate enables RFC 5861 stale-while-revalidate
// semantics: an expired entry whose Expiration is no older than window
// is served from cache immediately while a single background goroutine
// refreshes it from the origin. Concurrent stale hits coalesce so only
// one refresh runs per key at a time. Defaults to 0 (off), in which
// case expired entries continue to fall through to the existing
// release-and-miss path.
func ClientWithStaleWhileRevalidate(window time.Duration) ClientOption {
return func(c *Client) error {
if window < 0 {
return fmt.Errorf("cache client stale-while-revalidate window %v is invalid", window)
}
c.staleWindow = window
return nil
}
}
// ClientWithRespectCacheControl makes the middleware honor a small but
// useful subset of RFC 7234 Cache-Control directives on both requests
// and responses:
//
// - Request Cache-Control: no-store -> bypass the cache entirely
// (no lookup, no store).
// - Request Cache-Control: no-cache -> skip the cache lookup so the
// handler always runs, but still store the response.
// - Response Cache-Control: no-store, no-cache, or private -> do not
// store the response.
// - Response Cache-Control: s-maxage=N / max-age=N -> override the
// client's default TTL for this response (s-maxage wins, matching
// shared-cache semantics).
//
// Defaults off so existing applications that emit Cache-Control purely
// for downstream clients see no behavior change.
func ClientWithRespectCacheControl() ClientOption {
return func(c *Client) error {
c.respectCacheControl = true
return nil
}
}
// ClientWithMaxBodySize caps the response body bytes the middleware will
// buffer and cache. Responses that grow past the limit are still
// streamed to the client untouched, but their buffered copy is dropped
// and the entry is not stored. Defaults to no limit (0) for backward
// compatibility; that default lets a single oversized response (a
// download, an unbounded stream) hold its bytes in memory until the
// handler returns, so set a cap for any endpoint that can emit large
// payloads.
func ClientWithMaxBodySize(size int) ClientOption {
return func(c *Client) error {
if size <= 0 {
return fmt.Errorf("cache client max body size %d must be greater than 0", size)
}
c.maxBodySize = size
return nil
}
}
type responseWriter struct {
http.ResponseWriter
statusCode int
body bytes.Buffer
header http.Header
maxBodySize int
exceeded bool
wrote bool
}