/
HttpCacheTest.java
3551 lines (3020 loc) · 129 KB
/
HttpCacheTest.java
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) 2023 Moataz Abdelnasser
*
* 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 com.github.mizosoft.methanol;
import static com.github.mizosoft.methanol.MutableRequest.GET;
import static com.github.mizosoft.methanol.internal.cache.HttpDates.formatHttpDate;
import static com.github.mizosoft.methanol.testing.TestUtils.deflate;
import static com.github.mizosoft.methanol.testing.TestUtils.gzip;
import static com.github.mizosoft.methanol.testing.verifiers.Verifiers.verifyThat;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.function.Predicate.isEqual;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import com.github.mizosoft.methanol.CacheAwareResponse.CacheStatus;
import com.github.mizosoft.methanol.HttpCache.Listener;
import com.github.mizosoft.methanol.HttpCache.Stats;
import com.github.mizosoft.methanol.HttpCache.StatsRecorder;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.EventCategory;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnNetworkUse;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnReadFailure;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnReadSuccess;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnRequest;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnResponse;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnWriteFailure;
import com.github.mizosoft.methanol.HttpCacheTest.RecordingListener.OnWriteSuccess;
import com.github.mizosoft.methanol.Methanol.Interceptor;
import com.github.mizosoft.methanol.internal.Utils;
import com.github.mizosoft.methanol.internal.cache.CacheWritingPublisher;
import com.github.mizosoft.methanol.internal.cache.DiskStore;
import com.github.mizosoft.methanol.internal.cache.InternalStorageExtension;
import com.github.mizosoft.methanol.internal.cache.MemoryStore;
import com.github.mizosoft.methanol.internal.cache.Store;
import com.github.mizosoft.methanol.testing.Logging;
import com.github.mizosoft.methanol.testing.MockWebServerExtension.UseHttps;
import com.github.mizosoft.methanol.testing.TestException;
import com.github.mizosoft.methanol.testing.store.StoreConfig.FileSystemType;
import com.github.mizosoft.methanol.testing.store.StoreConfig.StoreType;
import com.github.mizosoft.methanol.testing.store.StoreContext;
import com.github.mizosoft.methanol.testing.store.StoreExtension;
import com.github.mizosoft.methanol.testing.store.StoreExtension.StoreParameterizedTest;
import com.github.mizosoft.methanol.testing.store.StoreSpec;
import com.github.mizosoft.methanol.testing.verifiers.ResponseVerifier;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.PushPromiseHandler;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import mockwebserver3.Dispatcher;
import mockwebserver3.MockResponse;
import mockwebserver3.QueueDispatcher;
import mockwebserver3.RecordedRequest;
import mockwebserver3.SocketPolicy;
import okhttp3.Headers;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.assertj.core.api.ObjectAssert;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.function.ThrowingConsumer;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@Timeout(10)
@ExtendWith(StoreExtension.class)
class HttpCacheTest extends AbstractHttpCacheTest {
/**
* Status codes that are cacheable by default (i.e. heuristically cacheable). From rfc7231 section
* 6.1:
*
* <pre>{@code
* Responses with status codes that are defined as cacheable by default (e.g., 200, 203, 204, 206,
* 300, 301, 404, 405, 410, 414, and 501 in this specification) can be reused by a cache with
* heuristic expiration unless otherwise indicated by the method definition or explicit cache
* controls [RFC7234]; all other status codes are not cacheable by default.
* }</pre>
*/
private static final Set<Integer> CACHEABLE_BY_DEFAULT_CODES =
Set.of(200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501);
static {
Logging.disable(HttpCache.class, DiskStore.class, CacheWritingPublisher.class);
}
private HttpCache cache;
private void setUpCache(Store store) {
setUpCache(store, null, null);
}
private void setUpCache(Store store, @Nullable StatsRecorder statsRecorder) {
setUpCache(store, statsRecorder, null);
}
private void setUpCache(
Store store, @Nullable StatsRecorder statsRecorder, @Nullable Listener listener) {
var cacheBuilder =
HttpCache.newBuilder()
.clock(clock)
.cacheOn(InternalStorageExtension.singleton(new EditAwaitableStore(store, editAwaiter)))
.executor(executor);
if (statsRecorder != null) {
cacheBuilder.statsRecorder(statsRecorder);
}
if (listener != null) {
cacheBuilder.listener(listener);
}
cache = cacheBuilder.build();
client = clientBuilder.cache(cache).build();
}
@AfterEach
void tearDown() throws IOException {
if (cache != null) {
cache.close();
}
}
@Test
void buildWithMemoryStore() throws IOException {
try (var cache = HttpCache.newBuilder().cacheOnMemory(12).build()) {
var store = cache.store();
assertThat(store).isInstanceOf(MemoryStore.class);
assertThat(store.maxSize()).isEqualTo(12);
assertThat(store.executor()).isEmpty();
assertThat(cache.directory()).isEmpty();
assertThat(cache.size()).isZero();
}
}
@Test
void buildWithDiskStore(@TempDir Path dir) throws IOException {
try (var cache = HttpCache.newBuilder().cacheOnDisk(dir, 12).executor(Runnable::run).build()) {
var store = cache.store();
assertThat(store).isInstanceOf(DiskStore.class);
assertThat(store.maxSize()).isEqualTo(12);
assertThat(cache.directory()).hasValue(dir);
assertThat(cache.executor()).isEqualTo(store.executor());
}
}
@StoreParameterizedTest
void cacheGetWithMaxAge(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setBody("Pikachu").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
clock.advance(Duration.ofSeconds(1));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(999));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(1));
server.enqueue(new MockResponse().setBody("Eevee").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
clock.advance(Duration.ofSeconds(3));
server.enqueue(new MockResponse().setBody("Eevee").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
}
@StoreParameterizedTest
void cacheGetWithExpires(Store store) throws Exception {
setUpCache(store);
var timeResponseReceived = toUtcDateTime(clock.instant());
server.enqueue(
new MockResponse()
.setHeader("Expires", formatHttpDate(timeResponseReceived.plusDays(1)))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
clock.advance(Duration.ofHours(12));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofHours(12).minusMillis(1));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(1));
server.enqueue(
new MockResponse()
.setHeader("Expires", formatHttpDate(timeResponseReceived.plusDays(1)))
.setBody("Eevee"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
clock.advance(Duration.ofDays(1).plusMillis(1));
server.enqueue(
new MockResponse()
.setHeader("Expires", formatHttpDate(timeResponseReceived.plusDays(1)))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Pikachu");
}
@StoreParameterizedTest
void cacheGetWithExpiresAndDate(Store store) throws Exception {
setUpCache(store);
var timeResponseGenerated = toUtcDateTime(clock.instant());
clock.advance(Duration.ofHours(12));
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(timeResponseGenerated))
.setHeader("Expires", formatHttpDate(timeResponseGenerated.plusDays(1)))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
clock.advance(Duration.ofHours(10));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofHours(2).minusMillis(1));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(1));
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(timeResponseGenerated))
.setHeader("Expires", formatHttpDate(timeResponseGenerated.plusDays(1)))
.setBody("Eevee"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
clock.advance(Duration.ofDays(1).plusMillis(1));
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(timeResponseGenerated))
.setHeader("Expires", formatHttpDate(timeResponseGenerated.plusDays(1)))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Pikachu");
}
@StoreParameterizedTest
@UseHttps
void cacheSecureGetWithMaxAge(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setBody("Pikachu").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
clock.advance(Duration.ofSeconds(1));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(999));
verifyThat(send(serverUri)).isCacheHit().hasBody("Pikachu");
clock.advance(Duration.ofMillis(1));
server.enqueue(new MockResponse().setBody("Eevee").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
clock.advance(Duration.ofSeconds(3));
server.enqueue(new MockResponse().setBody("Eevee").setHeader("Cache-Control", "max-age=2"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Eevee");
}
@StoreParameterizedTest
void conditionalHitForGetWithExpires(Store store) throws Exception {
setUpCache(store);
// Expire one day from "now"
var oneDayFromNow = clock.instant().plus(Duration.ofDays(1));
server.enqueue(
new MockResponse()
.setHeader("Expires", instantToHttpDateString(oneDayFromNow))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Make response stale
clock.advance(Duration.ofDays(2));
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
verifyThat(send(serverUri)).isConditionalHit().hasBody("Pikachu");
}
@StoreParameterizedTest
@UseHttps
void conditionalHitForSecureGetWithExpires(Store store) throws Exception {
setUpCache(store);
// Expire one day from "now"
var oneDayFromNow = clock.instant().plus(Duration.ofDays(1));
server.enqueue(
new MockResponse()
.setHeader("Expires", instantToHttpDateString(oneDayFromNow))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Make response stale
clock.advance(Duration.ofDays(2));
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
verifyThat(send(serverUri)).isConditionalHit().hasBody("Pikachu").isCachedWithSsl();
}
@StoreParameterizedTest
void responseIsFreshenedOnConditionalHit(Store store) throws Exception {
setUpCache(store);
// Warning 113 is stored (e.g. may come from a proxy's cache) but it's removed on freshening
server.enqueue(
new MockResponse()
.setHeader("Warning", "113 - \"Heuristic Expiration\"")
.setHeader("X-Version", "v1")
.setHeader("Content-Type", "text/plain")
.setHeader("Cache-Control", "max-age=1")
.setBody("Jigglypuff"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Jigglypuff");
// Make response stale
clock.advanceSeconds(2);
server.enqueue(
new MockResponse().setResponseCode(HTTP_NOT_MODIFIED).setHeader("X-Version", "v2"));
verifyThat(send(serverUri)).isConditionalHit().hasBody("Jigglypuff");
var instantRevalidationSentAndReceived = clock.instant();
verifyThat(awaitCacheHit())
.isCacheHit()
.hasBody("Jigglypuff")
.containsHeader("X-Version", "v2")
.requestWasSentAt(instantRevalidationSentAndReceived)
.responseWasReceivedAt(instantRevalidationSentAndReceived);
}
@StoreParameterizedTest
void successfulRevalidationWithZeroContentLength(Store store) throws Exception {
setUpCache(store);
server.enqueue(
new MockResponse()
.setHeader("X-Version", "v1")
.setHeader("Cache-Control", "max-age=1")
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Make response stale
clock.advanceSeconds(2);
server.enqueue(
new MockResponse()
.setResponseCode(HTTP_NOT_MODIFIED)
.setHeader("X-Version", "v2")
.setHeader("Content-Length", "0")); // This is wrong, but some servers do it
verifyThat(send(serverUri))
.isConditionalHit()
.hasBody("Pikachu")
.containsHeader("X-Version", "v2")
.containsHeader(
"Content-Length", "Pikachu".length()) // Correct Content-Length isn't replaced
.networkResponse()
.containsHeader("Content-Length", "0");
verifyThat(awaitCacheHit())
.isCacheHit()
.hasBody("Pikachu")
.containsHeader("X-Version", "v2")
.containsHeader("Content-Length", "Pikachu".length());
}
@StoreParameterizedTest
void prohibitNetworkOnRequiredValidation(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setHeader("Cache-Control", "max-age=1").setBody("123"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("123");
// Make response stale
clock.advanceSeconds(2);
verifyThat(send(GET(serverUri).header("Cache-Control", "only-if-cached")))
.isCacheUnsatisfaction()
.hasBody("");
}
@ParameterizedTest
@ValueSource(
strings = {
"Connection",
"Proxy-Connection",
"Keep-Alive",
"WWW-Authenticate",
"Proxy-Authenticate",
"Proxy-Authorization",
"TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Content-Location",
"Content-MD5",
"ETag",
"Content-Encoding",
"Content-Range",
"Content-Type",
"Content-Length",
"X-Frame-Options",
"X-XSS-Protection",
"X-Content-*",
"X-Webkit-*"
})
@StoreSpec(tested = StoreType.DISK, fileSystem = FileSystemType.SYSTEM)
void retainedStoredHeadersOnRevalidation(String headerName, Store store) throws Exception {
clientBuilder.autoAcceptEncoding(false);
setUpCache(store);
// Replace '*' in header prefixes.
headerName = headerName.replace("*", "Something");
// Validity of the value's format isn't relevant for this test. The HTTP client however
// complains if Content-Length isn't correct.
var cacheHeaderValue =
"Content-Length".equalsIgnoreCase(headerName) ? "Pikachu".length() : "v1";
var networkHeaderValue = "Content-Length".equalsIgnoreCase(headerName) ? 0 : "v2";
server.enqueue(
new MockResponse()
.setHeader(headerName, cacheHeaderValue)
.setHeader("Cache-Control", "max-age=1")
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Make response stale.
clock.advanceSeconds(2);
server.enqueue(
new MockResponse()
.setResponseCode(HTTP_NOT_MODIFIED)
.setHeader(headerName, networkHeaderValue));
verifyThat(send(serverUri))
.isConditionalHit()
.containsHeader(headerName, cacheHeaderValue.toString()) // The stored header is retained.
.hasBody("Pikachu");
}
private enum ValidatorConfig {
ETAG(true, false),
LAST_MODIFIED(false, true),
ALL(true, true),
NONE(false, false);
final boolean etag;
final boolean lastModified;
ValidatorConfig(boolean etag, boolean lastModified) {
this.etag = etag;
this.lastModified = lastModified;
}
Headers getValidators(int etagVersion, Instant now) {
var validators = new Headers.Builder();
if (etag) {
validators.add("ETag", Integer.toString(etagVersion));
}
if (lastModified) {
validators.add("Last-Modified", now);
}
return validators.build();
}
}
@StoreParameterizedTest
void revalidationFromStale(StoreContext storeContext) throws Throwable {
testForEachValidator(
storeContext,
config -> {
var request = GET(serverUri);
assertRevalidation(request, config, true);
});
}
@StoreParameterizedTest
void failedRevalidationFromStale(StoreContext storeContext) throws Throwable {
testForEachValidator(
storeContext,
config -> {
var request = GET(serverUri);
assertFailedRevalidation(request, config, true);
});
}
@StoreParameterizedTest
void revalidationForcedByNoCache(StoreContext storeContext) throws Throwable {
testForEachValidator(
storeContext,
config -> {
var request = GET(serverUri).header("Cache-Control", "no-cache");
assertRevalidation(request, config, false);
});
}
@StoreParameterizedTest
void failedRevalidationForcedByNoCache(StoreContext storeContext) throws Throwable {
testForEachValidator(
storeContext,
config -> {
var request = GET(serverUri).header("Cache-Control", "no-cache");
assertFailedRevalidation(request, config, false);
});
}
private void testForEachValidator(
StoreContext storeContext, ThrowingConsumer<ValidatorConfig> tester) throws Throwable {
for (var config : ValidatorConfig.values()) {
try {
setUpCache(storeContext.createAndRegisterStore());
tester.accept(config);
// Clean workspace for next config
cache.dispose();
} catch (AssertionError failed) {
fail(config.toString(), failed);
}
}
}
private void assertRevalidation(
HttpRequest triggeringRequest, ValidatorConfig config, boolean makeStale)
throws IOException, InterruptedException {
var validators = config.getValidators(1, clock.instant());
// Make Last-Modified 1 second prior to "now"
clock.advanceSeconds(1);
server.enqueue(
new MockResponse()
.setHeaders(validators)
.setHeader("Cache-Control", "max-age=2")
.setHeader("X-Version", "v1")
.setBody("STONKS!"));
verifyThat(send(serverUri)) //
.isCacheMiss()
.hasBody("STONKS!")
.containsHeader("X-Version", "v1");
server.takeRequest(); // Remove initial request
// Make stale or retain freshness
clock.advanceSeconds(makeStale ? 3 : 1);
server.enqueue(
new MockResponse().setResponseCode(HTTP_NOT_MODIFIED).setHeader("X-Version", "v2"));
verifyThat(send(triggeringRequest))
.isConditionalHit()
.hasBody("STONKS!")
.containsHeader("X-Version", "v2");
var sentRequest = server.takeRequest();
// If-Modified-Since is only sent if Last-Modified is present.
if (config.lastModified) {
assertThat(sentRequest.getHeaders().getInstant("If-Modified-Since"))
.isEqualTo(validators.getInstant("Last-Modified"));
}
// If-Non-Match is used only if ETag is present.
if (config.etag) {
assertThat(sentRequest.getHeader("If-None-Match")).isEqualTo("1");
}
}
private void assertFailedRevalidation(
HttpRequest triggeringRequest, ValidatorConfig config, boolean makeStale)
throws IOException, InterruptedException {
var validators1 = config.getValidators(1, clock.instant());
clock.advanceSeconds(1);
// Use different etag and Last-Modified for the revalidation response
var validators2 = config.getValidators(2, clock.instant());
clock.advanceSeconds(1);
server.enqueue(
new MockResponse()
.setHeaders(validators1)
.setHeader("Cache-Control", "max-age=2")
.setHeader("X-Version", "v1")
.setBody("STONKS!"));
verifyThat(send(serverUri)) //
.isCacheMiss()
.hasBody("STONKS!")
.containsHeader("X-Version", "v1");
server.takeRequest(); // Remove initial request
// Make stale or retain freshness
clock.advanceSeconds(makeStale ? 3 : 1);
server.enqueue(
new MockResponse()
.setHeaders(validators2)
.setHeader("Cache-Control", "max-age=2")
.setHeader("X-Version", "v2")
.setBody("DOUBLE STONKS!"));
verifyThat(send(triggeringRequest))
.isConditionalMiss()
.hasBody("DOUBLE STONKS!")
.containsHeader("X-Version", "v2")
.containsHeaders(validators2.toMultimap())
.cacheResponse() // This is the invalidated cache response
.containsHeader("X-Version", "v1")
.containsHeaders(validators1.toMultimap());
// Retain updated response's freshness
clock.advanceSeconds(1);
verifyThat(send(serverUri))
.isCacheHit()
.hasBody("DOUBLE STONKS!")
.containsHeader("X-Version", "v2")
.containsHeaders(validators2.toMultimap());
var sentRequest = server.takeRequest();
if (config.lastModified) {
assertThat(sentRequest.getHeaders().getInstant("If-Modified-Since"))
.isEqualTo(validators1.getInstant("Last-Modified"));
}
if (config.etag) {
assertThat(sentRequest.getHeader("If-None-Match")).isEqualTo("1");
}
}
@StoreParameterizedTest
void preconditionFieldsAreNotVisibleOnServedResponse(Store store) throws Exception {
setUpCache(store);
var lastModifiedString = instantToHttpDateString(clock.instant().minusSeconds(1));
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1")
.setHeader("ETag", "1")
.setHeader("Last-Modified", lastModifiedString));
verifyThat(send(serverUri)).isCacheMiss();
// Make response stale
clock.advanceSeconds(2);
// Precondition fields aren't visible on the served response's request.
// The preconditions are however visible from the network response's request.
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
verifyThat(send(serverUri))
.isConditionalHit()
.doesNotContainRequestHeader("If-None-Match")
.doesNotContainRequestHeader("If-Modified-Since")
.networkResponse()
.containsRequestHeader("If-None-Match", "1")
.containsRequestHeader("If-Modified-Since", lastModifiedString);
}
@StoreParameterizedTest
void pastExpires(Store store) throws Exception {
setUpCache(store);
var date = toUtcDateTime(clock.instant());
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Expires", formatHttpDate(date.minusSeconds(10)))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Negative freshness lifetime caused by past Expires triggers revalidation
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Expires", formatHttpDate(date.minusSeconds(10)))
.setBody("Psyduck"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Psyduck");
}
@StoreParameterizedTest
void invalidExpiresMakesResponseStale(Store store) throws Exception {
setUpCache(store);
var date = toUtcDateTime(clock.instant());
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Expires", -1)
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Negative freshness lifetime caused by invalid Expires triggers revalidation.
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Expires", -1)
.setBody("Psyduck"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Psyduck");
clock.advanceSeconds(1);
// Staleness rules should still apply in case of invalid 'Expires'.
verifyThat(
send(
GET(serverUri)
.cacheControl(
CacheControl.newBuilder().maxStale(Duration.ofSeconds(1)).build())))
.isCacheHit()
.hasBody("Psyduck");
}
@StoreParameterizedTest
void heuristicFreshnessWithFutureLastModified(Store store) throws Exception {
setUpCache(store);
var date = toUtcDateTime(clock.instant());
var lastModified = date.plusSeconds(10);
// Don't include explicit freshness to trigger heuristics, which relies on Last-Modified
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Last-Modified", formatHttpDate(lastModified))
.setBody("Pikachu"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Pikachu");
// Negative heuristic lifetime caused by future Last-Modified triggers revalidation
server.enqueue(
new MockResponse()
.setHeader("Date", formatHttpDate(date))
.setHeader("Last-Modified", formatHttpDate(lastModified))
.setBody("Psyduck"));
verifyThat(send(serverUri))
.isConditionalMiss()
.hasBody("Psyduck")
.networkResponse()
.containsRequestHeader("If-Modified-Since", formatHttpDate(lastModified));
}
@StoreParameterizedTest
void relaxMaxAgeWithRequest(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setHeader("Cache-Control", "max-age=1").setBody("tesla"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("tesla");
// Make response stale
clock.advanceSeconds(2);
// Relaxed max-age retains freshness
var request = GET(serverUri).header("Cache-Control", "max-age=3");
verifyThat(send(request)).isCacheHit().hasBody("tesla");
}
@StoreParameterizedTest
void constrainMaxAgeWithRequest(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setHeader("Cache-Control", "max-age=2").setBody("tesla"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("tesla");
// Retain freshness
clock.advanceSeconds(1);
verifyThat(send(serverUri)).isCacheHit().hasBody("tesla");
// Constrain max-age so that the response becomes stale
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
var request = GET(serverUri).header("Cache-Control", "max-age=1");
verifyThat(send(request)).isConditionalHit().hasBody("tesla");
}
@StoreParameterizedTest
void constrainFreshnessWithMinFresh(Store store) throws Exception {
setUpCache(store);
var lastModifiedInstant = clock.instant();
clock.advanceSeconds(2);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=3")
.setHeader("Last-Modified", instantToHttpDateString(lastModifiedInstant))
.setBody("spaceX"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("spaceX");
server.takeRequest(); // Drop request
// Set freshness to 2 seconds
clock.advanceSeconds(1);
verifyThat(send(serverUri)).isCacheHit().hasBody("spaceX");
var requestMinFresh2 = GET(serverUri).header("Cache-Control", "min-fresh=2");
verifyThat(send(requestMinFresh2))
.isCacheHit() // min-fresh is satisfied
.hasBody("spaceX");
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=3")
.setHeader("Last-Modified", instantToHttpDateString(lastModifiedInstant))
.setBody("tesla"));
var requestMinFresh3 = GET(serverUri).header("Cache-Control", "min-fresh=3");
verifyThat(send(requestMinFresh3))
.isConditionalMiss() // min-fresh isn't satisfied
.hasBody("tesla");
var sentRequest = server.takeRequest();
assertThat(sentRequest.getHeaders().getInstant("If-Modified-Since"))
.isEqualTo(lastModifiedInstant);
}
@StoreParameterizedTest
void acceptingStalenessWithMaxStale(Store store) throws Exception {
setUpCache(store);
server.enqueue(
new MockResponse().setHeader("Cache-Control", "max-age=1").setBody("stale on a scale"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("stale on a scale");
// Make response stale by 2 seconds
clock.advanceSeconds(3);
BiConsumer<CacheControl, UnaryOperator<ResponseVerifier<String>>> assertStaleness =
(cacheControl, cacheStatusAssert) -> {
var request = GET(serverUri).cacheControl(cacheControl);
var response =
cacheStatusAssert
.apply(verifyThat(sendUnchecked(request)))
.hasBody("stale on a scale");
// Must put a warning only if not revalidated
if (response.getCacheAwareResponse().cacheStatus() == CacheStatus.HIT) {
response.containsHeader("Warning", "110 - \"Response is Stale\"");
} else {
response.doesNotContainHeader("Warning");
}
};
// Allow any staleness -> HIT
assertStaleness.accept(CacheControl.parse("max-stale"), ResponseVerifier::isCacheHit);
// Allow 3 seconds of staleness -> HIT
assertStaleness.accept(CacheControl.parse("max-stale=3"), ResponseVerifier::isCacheHit);
// Allow 2 seconds of staleness -> HIT
assertStaleness.accept(CacheControl.parse("max-stale=2"), ResponseVerifier::isCacheHit);
// Allow 1 second of staleness -> CONDITIONAL_HIT as staleness is 2
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
assertStaleness.accept(CacheControl.parse("max-stale=1"), ResponseVerifier::isConditionalHit);
}
@StoreParameterizedTest
void mustRevalidateWhenStaleWithMaxStale(Store store) throws Exception {
setUpCache(store);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1, must-revalidate")
.setBody("Popeye"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Popeye");
// Make response stale.
clock.advanceSeconds(2);
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
var request1 =
GET(serverUri)
.cacheControl(CacheControl.newBuilder().maxStale(Duration.ofSeconds(5)).build());
verifyThat(send(request1)).isConditionalHit().hasBody("Popeye");
// Make response stale.
clock.advanceSeconds(2);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1, must-revalidate")
.setBody("Olive Oyl"));
var request2 =
GET(serverUri)
.cacheControl(CacheControl.newBuilder().maxStale(Duration.ofSeconds(5)).build());
verifyThat(send(request2)).isConditionalMiss().hasBody("Olive Oyl");
}
@StoreParameterizedTest
void mustRevalidateWhenStaleWithStaleWhileRevalidateAndStaleIfErrorOnResponse(Store store)
throws Exception {
setUpCache(store);
// Although Cache-Control here doesn't make much sense, it ensures server's must-revalidate
// never permits stale responses, even if allowed by the server itself.
server.enqueue(
new MockResponse()
.setHeader(
"Cache-Control",
"max-age=1, must-revalidate, stale-while-revalidate=5, stale-if-error=5")
.setBody("Popeye"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Popeye");
// Make response stale.
clock.advanceSeconds(2);
server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_MODIFIED));
verifyThat(send(serverUri)).isConditionalHit().hasBody("Popeye");
// Make response stale.
clock.advanceSeconds(2);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1, must-revalidate")
.setBody("Olive Oyl"));
verifyThat(send(serverUri)).isConditionalMiss().hasBody("Olive Oyl");
}
@StoreParameterizedTest
void mustRevalidateWhenStaleWithStaleIfErrorOnRequest(Store store) throws Exception {
setUpCache(store);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1, must-revalidate")
.setBody("Popeye"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Popeye");
// Make response stale.
clock.advanceSeconds(2);
client = clientBuilder.backendInterceptor(new FaultyInterceptor(TestException::new)).build();
var request = GET(serverUri).header("Cache-Control", "stale-if-error=5");
assertThatThrownBy(() -> send(request)).isInstanceOf(TestException.class);
}
@StoreParameterizedTest
void mustRevalidateWhenFresh(Store store) throws Exception {
setUpCache(store);
server.enqueue(
new MockResponse()
.setHeader("Cache-Control", "max-age=1, must-revalidate")
.setBody("Picasso"));
verifyThat(send(serverUri)).isCacheMiss().hasBody("Picasso");
// must-revalidate only applies to stale responses.
verifyThat(send(serverUri)).isCacheHit().hasBody("Picasso");
}
@StoreParameterizedTest
void cacheTwoPathsSameUri(Store store) throws Exception {
setUpCache(store);
server.enqueue(new MockResponse().setHeader("Cache-Control", "max-age=1").setBody("alpha"));
verifyThat(send(serverUri.resolve("/a"))).isCacheMiss().hasBody("alpha");
server.enqueue(new MockResponse().setHeader("Cache-Control", "max-age=1").setBody("beta"));
verifyThat(send(serverUri.resolve("/b"))).isCacheMiss().hasBody("beta");
verifyThat(send(serverUri.resolve("/a"))).isCacheHit().hasBody("alpha");
verifyThat(send(serverUri.resolve("/b"))).isCacheHit().hasBody("beta");
}
@StoreParameterizedTest
void preventCachingByNoStoreInResponse(Store store) throws Exception {
setUpCache(store);