-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroundtripper_test.go
More file actions
1047 lines (983 loc) · 35.9 KB
/
roundtripper_test.go
File metadata and controls
1047 lines (983 loc) · 35.9 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
// Copyright (c) 2026 Bart Venter <72999113+bartventer@users.noreply.github.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpcache
import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"sync/atomic"
"testing"
"time"
"github.com/bartventer/httpcache/internal"
"github.com/bartventer/httpcache/internal/testutil"
"github.com/bartventer/httpcache/store"
"github.com/bartventer/httpcache/store/memcache"
)
func mockTransport(fields func(rt *transport)) *transport {
rt := &transport{
cache: &internal.MockResponseCache{},
upstream: http.DefaultTransport,
swrTimeout: DefaultSWRTimeout,
logger: internal.NewLogger(
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
),
ce: internal.NewCacheabilityEvaluator(),
rmc: &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return true },
},
vm: &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
},
uk: &internal.MockCacheKeyer{
CacheKeyFunc: func(u *url.URL) string { return "key" },
},
fc: &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: false,
Age: &internal.Age{},
UsefulLife: 60 * time.Second,
}
},
},
siep: &internal.MockStaleIfErrorPolicy{},
ci: &internal.MockCacheInvalidator{},
rs: &internal.MockResponseStorer{},
vrh: &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
return resp, nil
},
},
clock: &internal.MockClock{NowResult: time.Now()},
}
if fields != nil {
fields(rt)
}
return rt
}
var FakeResponseRef = &internal.ResponseRef{}
func assertCacheStatus(t *testing.T, resp *http.Response, expectedStatus internal.CacheStatus) {
t.Helper()
status := resp.Header.Get(internal.CacheStatusHeader)
if status != expectedStatus.Value {
t.Errorf("expected cache status %s, got %s", expectedStatus, status)
}
}
func Test_transport_CacheMissAndStore(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=60")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("hello world"))
}))
defer server.Close()
mockCache := &internal.MockCache{
GetFunc: func(key string) ([]byte, error) { return nil, nil },
SetFunc: func(key string, entry []byte) error { return nil },
DeleteFunc: func(key string) error { return nil },
}
respCache := internal.NewResponseCache(mockCache)
rt := mockTransport(func(rt *transport) {
rt.cache = respCache
rt.upstream = http.DefaultTransport
rt.ce = internal.CacheabilityEvaluatorFunc(
func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) bool {
return true // Simulating a cacheable response
},
)
rt.rs = &internal.MockResponseStorer{
StoreResponseFunc: func(req *http.Request, resp *http.Response, key string, headers internal.ResponseRefs, reqTime, respTime time.Time, refIndex int) error {
return nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusMiss)
}
func Test_transport_CacheHit(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("should not hit origin server on cache hit")
}))
defer server.Close()
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=60"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
mockRespCache := &internal.MockResponseCache{
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
SetFunc: func(key string, entry *internal.Response) error { return nil },
DeleteFunc: func(key string) error { return nil },
}
rt := mockTransport(func(rt *transport) {
rt.cache = mockRespCache
rt.upstream = http.DefaultTransport
})
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusHit)
}
func Test_transport_CacheHit_Immutable(t *testing.T) {
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=60, immutable"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: false,
Age: &internal.Age{},
UsefulLife: 60 * time.Second,
}
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertNotNil(t, resp)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusHit)
}
func Test_transport_CacheHit_MustRevalidate_Stale(t *testing.T) {
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=0, must-revalidate"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
mockVHCalled := false
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{IsStale: true, Age: &internal.Age{}, UsefulLife: 0}
},
}
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
mockVHCalled = true
return resp, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertTrue(t, mockVHCalled)
testutil.AssertNotNil(t, resp)
}
func Test_transport_CacheHit_NoCacheUnqualified(t *testing.T) {
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=60, no-cache"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
mockVHCalled := false
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
mockVHCalled = true
return resp, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertTrue(t, mockVHCalled)
testutil.AssertNotNil(t, resp)
}
func Test_transport_CacheHit_NoCacheQualified_StripsFields(t *testing.T) {
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Cache-Control": []string{`max-age=60, no-cache="Foo,Bar"`},
"Foo": []string{"should-be-removed"},
"Bar": []string{"should-be-removed"},
"Baz": []string{"should-stay"},
},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, "", resp.Header.Get("Foo"))
testutil.AssertEqual(t, "", resp.Header.Get("Bar"))
testutil.AssertEqual(t, "should-stay", resp.Header.Get("Baz"))
}
func Test_transport_UnrecognizedSafeMethod_Error(t *testing.T) {
rt := mockTransport(func(rt *transport) {
rt.rmc = &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return false },
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, testutil.ErrSample
},
}
})
req, _ := http.NewRequest(http.MethodTrace, "http://example.com", nil) // TRACE is a safe method
resp, err := rt.RoundTrip(req)
testutil.RequireErrorIs(t, err, testutil.ErrSample)
testutil.AssertNil(t, resp)
}
func Test_transport_NotUnderstoodAndUnsafeMethod(t *testing.T) {
roundTripperCalled := false
invalidateCalled := false
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return nil, nil
},
}
rt.rmc = &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return false },
}
rt.ci = &internal.MockCacheInvalidator{
InvalidateCacheFunc: func(reqURL *url.URL, respHeader http.Header, headers internal.ResponseRefs, key string) {
invalidateCalled = true
},
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
roundTripperCalled = true
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: make(http.Header),
}, nil
},
}
})
req, _ := http.NewRequest(http.MethodDelete, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertTrue(t, roundTripperCalled)
testutil.AssertTrue(t, invalidateCalled)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusBypass)
}
func Test_transport_NotUnderstoodAndSafeMethod(t *testing.T) {
roundTripperCalled := false
rt := mockTransport(func(rt *transport) {
rt.rmc = &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return false },
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
roundTripperCalled = true
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: make(http.Header),
}, nil
},
}
})
req, _ := http.NewRequest(http.MethodTrace, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertTrue(t, roundTripperCalled)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusBypass)
}
func Test_transport_NonErrorStatusInvalidation(t *testing.T) {
invalidateCalled := false
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.rmc = &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return false },
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: make(http.Header),
}, nil
},
}
rt.ci = &internal.MockCacheInvalidator{
InvalidateCacheFunc: func(reqURL *url.URL, respHeader http.Header, headers internal.ResponseRefs, key string) {
invalidateCalled = true
},
}
})
req, _ := http.NewRequest(http.MethodDelete, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertTrue(t, invalidateCalled)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusBypass)
}
func Test_transport_NotUnderstoodAndRoundTripError(t *testing.T) {
roundTripperCalled := false
rt := mockTransport(func(rt *transport) {
rt.rmc = &internal.MockRequestMethodChecker{
IsRequestMethodUnderstoodFunc: func(req *http.Request) bool { return false },
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
roundTripperCalled = true
return nil, testutil.ErrSample
},
}
})
req, _ := http.NewRequest(http.MethodDelete, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireErrorIs(t, err, testutil.ErrSample)
testutil.AssertNil(t, resp)
testutil.AssertTrue(t, roundTripperCalled)
}
func Test_transport_OnlyIfCached504(t *testing.T) {
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) {
return nil, errors.New("cache miss")
},
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
req.Header.Set("Cache-Control", "only-if-cached")
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusGatewayTimeout, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusBypass)
}
func Test_transport_CacheMissWithError(t *testing.T) {
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) {
return nil, errors.New("cache miss")
},
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, testutil.ErrSample
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireErrorIs(t, err, testutil.ErrSample)
testutil.AssertNil(t, resp)
}
func Test_transport_RevalidationPath(t *testing.T) {
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=0"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: time.Now(),
ReceivedAt: time.Now(),
}
mockVHCalled := false
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: true,
Age: &internal.Age{
Value: 10 * time.Second,
Timestamp: time.Now().Add(-10 * time.Second),
},
UsefulLife: 0,
}
},
}
rt.clock = &internal.MockClock{NowResult: time.Now()}
rt.siep = &internal.MockStaleIfErrorPolicy{}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: make(http.Header),
}, nil
},
}
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
mockVHCalled = true
internal.CacheStatusRevalidated.ApplyTo(resp.Header)
return resp, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
testutil.AssertTrue(t, mockVHCalled)
assertCacheStatus(t, resp, internal.CacheStatusRevalidated)
}
func Test_transport_SWR_NormalPath(t *testing.T) {
base := time.Unix(0, 0).UTC()
// Simulate a stale cache entry with SWR, normal revalidation path (no timeout).
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=0, stale-while-revalidate=15"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: base.Add(-10 * time.Second),
ReceivedAt: base.Add(-10 * time.Second),
}
revalidateCalled := make(chan struct{}, 1)
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: true,
Age: &internal.Age{
Value: 10 * time.Second,
Timestamp: base.Add(-10 * time.Second),
},
UsefulLife: 0,
}
},
}
rt.clock = &internal.MockClock{NowResult: base.Add(5 * time.Second), SinceResult: 0}
rt.siep = &internal.MockStaleIfErrorPolicy{}
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
revalidateCalled <- struct{}{} // Signal that revalidation was called
return resp, nil
},
}
rt.swrTimeout = DefaultSWRTimeout
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: http.Header{},
}, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusStale)
select {
case <-revalidateCalled:
// Success: background revalidate called
case <-time.After(DefaultSWRTimeout):
t.Error("expected background revalidate to be called")
}
}
func Test_transport_SWR_NormalPathAndError(t *testing.T) {
base := time.Unix(0, 0).UTC()
// Simulate a stale cache entry with SWR, normal revalidation path with error.
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=0, stale-while-revalidate=15"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: base.Add(-10 * time.Second),
ReceivedAt: base.Add(-10 * time.Second),
}
swrTimeout := 100 * time.Millisecond
revalidateCalled := make(chan struct{}, 1)
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: true,
Age: &internal.Age{
Value: 10 * time.Second,
Timestamp: base.Add(-10 * time.Second),
},
UsefulLife: 0,
}
},
}
rt.clock = &internal.MockClock{NowResult: base.Add(5 * time.Second), SinceResult: 0}
rt.swrTimeout = swrTimeout
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
defer func() { revalidateCalled <- struct{}{} }() // Signal that revalidation was called
return nil, errors.New("revalidation error")
},
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, errors.New("network error") // Simulate an error during revalidation
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusStale)
select {
case <-revalidateCalled:
t.Error("expected background revalidate to not be called due to error")
case <-time.After(swrTimeout + 100*time.Millisecond):
// Success: revalidate was not called due to error
}
}
func Test_transport_SWR_Timeout(t *testing.T) {
base := time.Unix(0, 0).UTC()
// Simulate a stale cache entry with SWR, but timeout before revalidation.
storedResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Cache-Control": []string{"max-age=0, stale-while-revalidate=15"}},
Body: http.NoBody,
}
storedEntry := &internal.Response{
Data: storedResp,
RequestedAt: base.Add(-10 * time.Second),
ReceivedAt: base.Add(-10 * time.Second),
}
swrTimeout := 50 * time.Millisecond
revalidateCalled := make(chan struct{}, 1)
rt := mockTransport(func(rt *transport) {
rt.cache = &internal.MockResponseCache{
GetFunc: func(key string, req *http.Request) (*internal.Response, error) { return storedEntry, nil },
GetRefsFunc: func(key string) (internal.ResponseRefs, error) {
return internal.ResponseRefs{FakeResponseRef}, nil
},
}
rt.vm = &internal.MockVaryMatcher{
VaryHeadersMatchFunc: func(cachedHdrs internal.ResponseRefs, reqHdr http.Header) (int, bool) {
return 0, true
},
}
rt.fc = &internal.MockFreshnessCalculator{
CalculateFreshnessFunc: func(resp *http.Response, reqCC internal.CCRequestDirectives, resCC internal.CCResponseDirectives) *internal.Freshness {
return &internal.Freshness{
IsStale: true,
Age: &internal.Age{
Value: 10 * time.Second,
Timestamp: base.Add(-10 * time.Second),
},
UsefulLife: 0,
}
},
}
rt.clock = &internal.MockClock{NowResult: base.Add(5 * time.Second), SinceResult: 0}
rt.swrTimeout = swrTimeout
rt.vrh = &internal.MockValidationResponseHandler{
HandleValidationResponseFunc: func(ctx internal.RevalidationContext, req *http.Request, resp *http.Response) (*http.Response, error) {
revalidateCalled <- struct{}{} // Signal that revalidation was called
return resp, nil
},
}
rt.upstream = &internal.MockRoundTripper{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
time.Sleep(swrTimeout + 500*time.Millisecond) // Simulate long revalidation
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: http.Header{},
}, nil
},
}
})
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)
assertCacheStatus(t, resp, internal.CacheStatusStale)
select {
case <-revalidateCalled:
t.Error("expected background revalidate to not be called due to timeout")
case <-time.After(swrTimeout + 750*time.Millisecond):
// Success: revalidate was not called due to timeout
}
}
func Test_newTransport(t *testing.T) {
mockTransport := &internal.MockRoundTripper{}
l := slog.New(slog.DiscardHandler)
swrTimeout := 100 * time.Millisecond
mockCache := &internal.MockCache{}
rt := newTransport(mockCache, WithUpstream(mockTransport),
WithLogger(l),
WithSWRTimeout(swrTimeout),
)
testutil.RequireNotNil(t, rt)
testutil.AssertTrue(t, mockTransport == rt.(*transport).upstream)
testutil.AssertEqual(t, swrTimeout, rt.(*transport).swrTimeout)
}
func TestNewTransport_Panic(t *testing.T) {
testutil.RequirePanics(t, func() {
NewTransport(
"invalid-cache-dsn",
WithUpstream(http.DefaultTransport),
WithLogger(slog.New(slog.DiscardHandler)),
)
})
}
//nolint:cyclop // Acceptable complexity for a test function
func Test_transport_Vary(t *testing.T) {
etag := `W/"1234567890"`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Vary", "Accept-Language, Accept-Encoding, User-Agent")
w.Header().Set("Cache-Control", "max-age=60")
w.Header().Set("ETag", etag)
if inm := r.Header.Get("If-None-Match"); inm == etag {
w.WriteHeader(http.StatusNotModified)
return
}
w.WriteHeader(http.StatusOK)
lang := r.Header.Get("Accept-Language")
enc := r.Header.Get("Accept-Encoding")
ua := r.Header.Get("User-Agent")
switch {
case lang == "en-us" && enc == "gzip" && ua == "Go-http-client/1.1":
w.Write([]byte("hello world (en, gzip, go)"))
case lang == "en-us" && enc == "br" && ua == "Go-http-client/1.1":
w.Write([]byte("hello world (en, br, go)"))
case lang == "fr-fr" && enc == "gzip" && ua == "Go-http-client/1.1":
w.Write([]byte("bonjour le monde (fr, gzip, go)"))
case lang == "en-us" && enc == "gzip" && ua == "curl/8.0":
w.Write([]byte("hello world (en, gzip, curl)"))
default:
w.Write([]byte("variant"))
}
}))
defer server.Close()
rt := NewTransport("memcache://")
drivers := store.Drivers()
testutil.AssertEqual(t, 1, len(drivers), "expected exactly one driver to be registered")
for i, tc := range []struct {
lang, enc, ua, inmatch, wantBody, wantStatus string
}{
// Each unique combination should be a MISS first, then HIT
{"en-us", "gzip", "Go-http-client/1.1", "", "hello world (en, gzip, go)", "MISS"},
{"en-us", "gzip", "Go-http-client/1.1", etag, "hello world (en, gzip, go)", "HIT"},
{"en-us", "br", "Go-http-client/1.1", "", "hello world (en, br, go)", "MISS"},
{"en-us", "br", "Go-http-client/1.1", etag, "hello world (en, br, go)", "HIT"},
{"fr-fr", "gzip", "Go-http-client/1.1", "", "bonjour le monde (fr, gzip, go)", "MISS"},
{"fr-fr", "gzip", "Go-http-client/1.1", etag, "bonjour le monde (fr, gzip, go)", "HIT"},
{"en-us", "gzip", "curl/8.0", "", "hello world (en, gzip, curl)", "MISS"},
{"en-us", "gzip", "curl/8.0", etag, "hello world (en, gzip, curl)", "HIT"},
} {
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
req.Header.Set("Accept-Language", tc.lang)
req.Header.Set("Accept-Encoding", tc.enc)
req.Header.Set("User-Agent", tc.ua)
if tc.inmatch != "" {
req.Header.Set("If-None-Match", tc.inmatch)
}
resp, err := rt.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode, i)
testutil.AssertEqual(
t,
"Accept-Language, Accept-Encoding, User-Agent",
resp.Header.Get("Vary"),
i,
)
testutil.AssertEqual(t, tc.wantStatus, resp.Header.Get(internal.CacheStatusHeader), i)
body, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
testutil.AssertEqual(t, tc.wantBody, string(body), i)
}
}
// This test verifies that when a cached response is revalidated via a 304 Not
// Modified, the cache entry is updated with any new headers from the 304
// response, and subsequent requests can HIT the cache again until it becomes
// stale once more.
func Test_transport_RevalidationUpdatesCache(t *testing.T) {
var originCalls atomic.Int32
const etag = `"v1"`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
originCalls.Add(1)
// Revalidation path: client sends validator, server says cached body is still valid
if r.Header.Get("If-None-Match") == etag {
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "max-age=1")
w.Header().Set("Expires", time.Now().Add(1*time.Second).UTC().Format(http.TimeFormat))
w.WriteHeader(http.StatusNotModified)
return
}
// Initial fetch
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "max-age=1")
w.Header().Set("Expires", time.Now().Add(1*time.Second).UTC().Format(http.TimeFormat))
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("hello"))
}))
defer server.Close()
c := memcache.Open()
tr := newTransport(c)
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
tests := []struct {
name string
expectedStatusCode int
expectedCacheStatus string
expectedBody string
expectedOriginCalls int32
preReqFunc func()
}{
{
name: "Initial request should be a MISS",
expectedStatusCode: http.StatusOK,
expectedCacheStatus: internal.CacheStatusMiss.Value,
expectedBody: "hello",
expectedOriginCalls: 1,
},
{
name: "Second request should be a HIT",
expectedStatusCode: http.StatusOK,
expectedCacheStatus: internal.CacheStatusHit.Value,
expectedBody: "hello",
expectedOriginCalls: 1,
},
{
name: "After becoming stale, request should be REVALIDATED via 304",
expectedStatusCode: http.StatusOK,
expectedCacheStatus: internal.CacheStatusRevalidated.Value,
expectedBody: "hello",
expectedOriginCalls: 2,
preReqFunc: func() {
time.Sleep(1100 * time.Millisecond)
},
},
{
name: "After revalidation, request should be HIT again",
expectedStatusCode: http.StatusOK,
expectedCacheStatus: internal.CacheStatusHit.Value,
expectedBody: "hello",
expectedOriginCalls: 2,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if tc.preReqFunc != nil {
tc.preReqFunc()
}
resp, err := tr.RoundTrip(req)
testutil.RequireNoError(t, err)
testutil.AssertEqual(t, tc.expectedStatusCode, resp.StatusCode)
testutil.AssertEqual(
t,
tc.expectedCacheStatus,
resp.Header.Get(internal.CacheStatusHeader),
)
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
testutil.AssertEqual(t, tc.expectedBody, string(body))
testutil.AssertEqual(t, tc.expectedOriginCalls, originCalls.Load())
})
}
}
// Test_transport_Vary_MultipleHeaders verifies that the transport correctly
// handles multiple Vary headers that are sent as separate header lines
// (instead of a single comma-separated line). This is a common scenario in
// practice, and there was a bug where only the first Vary header line was
// being processed, causing incorrect cache hits when subsequent Vary headers
// were not considered.
// Regression test for: https://github.com/bartventer/httpcache/issues/32
func Test_transport_Vary_MultipleHeaders(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate server returning multiple separate Vary header lines
// (not comma-separated, but as distinct headers)
w.Header().Add("Vary", "Accept-Language")
w.Header().Add("Vary", "X-Compatibility-Date")
w.Header().Set("Cache-Control", "max-age=60")
w.WriteHeader(http.StatusOK)
lang := r.Header.Get("Accept-Language")
date := r.Header.Get("X-Compatibility-Date")
_, _ = fmt.Fprintf(w, "lang=%s date=%s", lang, date)
}))
defer server.Close()
c := memcache.Open()
tr := newTransport(c, WithLogger(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))))
makeReq := func(lang, date string) *http.Response {
req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
req.Header.Set("Accept-Language", lang)
req.Header.Set("X-Compatibility-Date", date)
resp, err := tr.RoundTrip(req)
testutil.RequireNoError(t, err)
return resp
}
// Request 1: MISS — first request for en-us + 2025-01-01
resp := makeReq("en-us", "2025-01-01")
testutil.AssertEqual(t, http.StatusOK, resp.StatusCode)