Skip to content

Truly independent web browser

LibHTTP: Store stale responses in the disk cache

Andreas Klingaaf20625d71c
diff --git a/Libraries/LibHTTP/Cache/CacheEntry.cpp b/Libraries/LibHTTP/Cache/CacheEntry.cpp
index 855e422ff29..39c59c237c7 100644
--- a/Libraries/LibHTTP/Cache/CacheEntry.cpp
+++ b/Libraries/LibHTTP/Cache/CacheEntry.cpp
@@ -156,13 +156,10 @@ ErrorOr<void> CacheEntryWriter::write_status_and_reason(u32 status_code, Optiona
m_path = path_for_cache_entry(m_disk_cache.cache_directory(), m_cache_key, m_vary_key);
m_temporary_path = LexicalPath::join(m_disk_cache.cache_directory().string(), ByteString::formatted("{}.tmp", m_path->basename()));
- auto freshness_lifetime = calculate_freshness_lifetime(status_code, response_headers, m_current_time_offset_for_testing);
- auto current_age = calculate_age(response_headers, m_request_time, m_response_time, m_current_time_offset_for_testing);
-
- // We can cache already-expired responses if there are other cache directives that allow us to revalidate the
- // response on subsequent requests. For example, `Cache-Control: max-age=0, must-revalidate`.
- if (cache_lifetime_status(request_headers, response_headers, freshness_lifetime, current_age) == CacheLifetimeStatus::Expired)
- return Error::from_string_literal("Response has already expired");
+ // NB: We store a response that is already stale too, even one that has no validator to revalidate it with. A
+ // request whose cache mode is "force-cache" or "only-if-cached" uses a stored response "not paying attention
+ // to staleness". A history traversal is such a request, and it can only show the page as it was if the
+ // response is here.
(void)FileSystem::remove(m_temporary_path->string(), FileSystem::RecursionMode::Disallowed);
auto unbuffered_file = TRY(Core::File::open(m_temporary_path->string(), Core::File::OpenMode::Write | Core::File::OpenMode::MustBeNew));
diff --git a/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt b/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt
index d204634b0b6..dc20bb2682b 100644
--- a/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt
+++ b/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt
@@ -1,5 +1,24 @@
-loaded document with subresource
+Case: no-cache with a validator
+loaded document with subresource and revalidated subresource and srcdoc subresource
loaded other document
-loaded document with subresource
+loaded document with subresource and revalidated subresource and srcdoc subresource
Requests the server saw for the document: 1
Requests the server saw for the subresource: 1
+Requests the server saw for the subresource fetched with Cache-Control: no-cache: 2
+Requests the server saw for the subresource of the srcdoc iframe: 1
+Case: no freshness information and no validator
+loaded document with subresource and revalidated subresource and srcdoc subresource
+loaded other document
+loaded document with subresource and revalidated subresource and srcdoc subresource
+Requests the server saw for the document: 1
+Requests the server saw for the subresource: 1
+Requests the server saw for the subresource fetched with Cache-Control: no-cache: 2
+Requests the server saw for the subresource of the srcdoc iframe: 1
+Case: max-age=0 without a validator
+loaded document with subresource and revalidated subresource and srcdoc subresource
+loaded other document
+loaded document with subresource and revalidated subresource and srcdoc subresource
+Requests the server saw for the document: 1
+Requests the server saw for the subresource: 1
+Requests the server saw for the subresource fetched with Cache-Control: no-cache: 2
+Requests the server saw for the subresource of the srcdoc iframe: 1
diff --git a/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html b/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html
index d909fbe76e0..54d1841762f 100644
--- a/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html
+++ b/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html
@@ -1,22 +1,30 @@
<!DOCTYPE html>
<script src="../include.js"></script>
-<iframe id="testFrame"></iframe>
+<body>
<script>
const server = httpTestServer();
// In test mode, the disk cache only stores responses to requests carrying this header.
const TEST_CACHE_ENABLED_HEADER = "X-Ladybird-Enable-Disk-Cache";
- // The echo path keys both the server-side request count and the disk cache entry. Give each run its own paths, so
- // parallel runner clones of this test don't count each other's requests.
- const id = uniqueID();
-
- // Both the document and the resource it fetches while it loads must be revalidated before a cache may use them
- // again. A history traversal back to the document must use the stored responses anyway.
- const MUST_REVALIDATE_HEADERS = {
- "Cache-Control": "no-cache",
- "Last-Modified": "Mon, 01 Jan 2024 00:00:00 GMT",
- };
+ // A history traversal back to a document must use the stored responses for the document and for the resource it
+ // fetches while it loads, whatever their freshness.
+ const CASES = [
+ // The responses must be revalidated before a cache may use them again.
+ {
+ name: "no-cache with a validator",
+ headers: { "Cache-Control": "no-cache", "Last-Modified": "Mon, 01 Jan 2024 00:00:00 GMT" },
+ },
+ // The responses are stale as soon as they arrive, and there is nothing to revalidate them with.
+ {
+ name: "no freshness information and no validator",
+ headers: {},
+ },
+ {
+ name: "max-age=0 without a validator",
+ headers: { "Cache-Control": "max-age=0" },
+ },
+ ];
function nextMessage() {
return new Promise(resolve => {
@@ -24,23 +32,50 @@
});
}
- promiseTest(async () => {
+ async function runCase({ name, headers }) {
+ // The echo path keys both the server-side request count and the disk cache entry. Give each run its own paths,
+ // so parallel runner clones of this test don't count each other's requests.
+ const id = uniqueID();
+
const requestCount = async url => (await fetch(server.recordedRequestCountURL(url))).json();
const subresourceURL = await server.createEcho("GET", `/history-traversal-subresource-${id}`, {
status: 200,
- headers: { ...MUST_REVALIDATE_HEADERS, "Content-Type": "text/plain" },
+ headers: { ...headers, "Content-Type": "text/plain" },
body: "subresource",
});
+ // A request that carries cache directives of its own keeps the freshness it asks for.
+ const revalidatedSubresourceURL = await server.createEcho("GET", `/history-traversal-revalidated-subresource-${id}`, {
+ status: 200,
+ headers: { ...headers, "Content-Type": "text/plain" },
+ body: "revalidated subresource",
+ });
+
+ // A srcdoc iframe document is not fetched, but loads like the document that contains it.
+ const srcdocSubresourceURL = await server.createEcho("GET", `/history-traversal-srcdoc-subresource-${id}`, {
+ status: 200,
+ headers: { ...headers, "Content-Type": "text/plain" },
+ body: "srcdoc subresource",
+ });
+
const documentURL = await server.createEcho("GET", `/history-traversal-document-${id}`, {
status: 200,
- headers: { ...MUST_REVALIDATE_HEADERS, "Content-Type": "text/html" },
+ headers: { ...headers, "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
window.onmessage = event => { location.href = event.data; };
- fetch(${JSON.stringify(subresourceURL)}, { headers: { ${JSON.stringify(TEST_CACHE_ENABLED_HEADER)}: "1" } })
- .then(response => response.text())
- .then(text => parent.postMessage("loaded document with " + text, "*"));
+ const cacheHeaders = { ${JSON.stringify(TEST_CACHE_ENABLED_HEADER)}: "1" };
+ const srcdocFetch = new Promise(resolve => { window.srcdocFetched = resolve; });
+ const srcdocFrame = document.createElement("iframe");
+ srcdocFrame.srcdoc = "<script>parent.srcdocFetched(fetch(" + JSON.stringify(${JSON.stringify(srcdocSubresourceURL)}) + ", { headers: " + JSON.stringify(cacheHeaders) + " }));<\\/script>";
+ document.documentElement.appendChild(srcdocFrame);
+ Promise.all([
+ fetch(${JSON.stringify(subresourceURL)}, { headers: cacheHeaders }),
+ fetch(${JSON.stringify(revalidatedSubresourceURL)}, { headers: { ...cacheHeaders, "Cache-Control": "no-cache" } }),
+ srcdocFetch,
+ ])
+ .then(responses => Promise.all(responses.map(response => response.text())))
+ .then(texts => parent.postMessage("loaded document with " + texts.join(" and "), "*"));
<\/script>`,
});
@@ -58,25 +93,37 @@
// this page can reach.
const diskCacheWasEnabledForNavigations = internals.setDiskCacheEnabledForNavigations(true);
- // Navigate the iframe to the document, which caches both the document and its subresource.
- const frame = document.getElementById("testFrame");
- let message = nextMessage();
- frame.src = documentURL;
- println(await message);
-
- // Navigate the iframe away, and then traverse back. The iframe does both itself, so that this works regardless
- // of whether the test page and the echo server are same-origin.
- message = nextMessage();
- frame.contentWindow.postMessage(otherDocumentURL, "*");
- println(await message);
+ const frame = document.createElement("iframe");
+ try {
+ // Navigate the iframe to the document, which caches both the document and its subresource.
+ println(`Case: ${name}`);
+ document.body.appendChild(frame);
+ let message = nextMessage();
+ frame.src = documentURL;
+ println(await message);
- message = nextMessage();
- frame.contentWindow.postMessage("back", "*");
- println(await message);
+ // Navigate the iframe away, and then traverse back. The iframe does both itself, so that this works regardless
+ // of whether the test page and the echo server are same-origin.
+ message = nextMessage();
+ frame.contentWindow.postMessage(otherDocumentURL, "*");
+ println(await message);
- internals.setDiskCacheEnabledForNavigations(diskCacheWasEnabledForNavigations);
+ message = nextMessage();
+ frame.contentWindow.postMessage("back", "*");
+ println(await message);
+ } finally {
+ internals.setDiskCacheEnabledForNavigations(diskCacheWasEnabledForNavigations);
+ }
println(`Requests the server saw for the document: ${await requestCount(documentURL)}`);
println(`Requests the server saw for the subresource: ${await requestCount(subresourceURL)}`);
+ println(`Requests the server saw for the subresource fetched with Cache-Control: no-cache: ${await requestCount(revalidatedSubresourceURL)}`);
+ println(`Requests the server saw for the subresource of the srcdoc iframe: ${await requestCount(srcdocSubresourceURL)}`);
+ frame.remove();
+ }
+
+ promiseTest(async () => {
+ for (const testCase of CASES)
+ await runCase(testCase);
});
</script>
diff --git a/Tests/LibWeb/Text/input/Cache/http-disk-cache.html b/Tests/LibWeb/Text/input/Cache/http-disk-cache.html
index 0278fbca980..f422da8f45f 100644
--- a/Tests/LibWeb/Text/input/Cache/http-disk-cache.html
+++ b/Tests/LibWeb/Text/input/Cache/http-disk-cache.html
@@ -148,12 +148,15 @@
}
})();
- // Responses without a Cache-Control or Expires header are not cached.
+ // Responses without a Cache-Control or Expires header are stored, but not reused.
await (async () => {
url = await createRequest("/cache-test/missing-headers");
response = await cacheFetch(url);
- expectCacheStatus(url, response, "not-cached");
+ expectCacheStatus(url, response, "written-to-cache");
+
+ response = await cacheFetch(url);
+ expectCacheStatus(url, response, "written-to-cache");
})();
// Responses with a no-store Cache-Control directive are not cached.
@@ -319,7 +322,7 @@
expectCacheStatus(url, response, "read-from-cache");
})();
- // Responses with an age equal to their max-age directive are not cached.
+ // Responses with an age equal to their max-age directive are stored, but not reused.
await (async () => {
url = await createRequest("/cache-test/response/max-age-expired", {
headers: {
@@ -329,7 +332,10 @@
});
response = await cacheFetch(url);
- expectCacheStatus(url, response, "not-cached");
+ expectCacheStatus(url, response, "written-to-cache");
+
+ response = await cacheFetch(url);
+ expectCacheStatus(url, response, "written-to-cache");
})();
// Responses with an age less than the requests's max-age directive are cached.
@@ -352,7 +358,7 @@
expectCacheStatus(url, response, "read-from-cache");
})();
- // Responses with an age equal to the request's max-age directive are not cached.
+ // Responses with an age equal to the request's max-age directive are stored, but not reused.
await (async () => {
url = await createRequest("/cache-test/request/max-age-expired", {
headers: {
@@ -361,12 +367,14 @@
},
});
- response = await cacheFetch(url, {
- headers: {
- "Cache-Control": "max-age=5",
- },
- });
- expectCacheStatus(url, response, "not-cached");
+ for (let i = 0; i < 2; ++i) {
+ response = await cacheFetch(url, {
+ headers: {
+ "Cache-Control": "max-age=5",
+ },
+ });
+ expectCacheStatus(url, response, "written-to-cache");
+ }
})();
// Responses with an age within the requests's max-stale directive are cached.
@@ -472,7 +480,7 @@
expectCacheStatus(url, response, "read-from-cache");
})();
- // Responses with an age outside of the requests's min-fresh directive are not cached.
+ // Responses with an age outside of the requests's min-fresh directive are stored, but not reused.
await (async () => {
url = await createRequest("/cache-test/request/min-fresh-expired", {
headers: {
@@ -489,7 +497,7 @@
"Cache-Control": "min-fresh=4",
},
});
- expectCacheStatus(url, response, "not-cached");
+ expectCacheStatus(url, response, "written-to-cache");
})();
// Incomplete responses are not cached.
diff --git a/Tests/LibWebView/test-webdriver-session-history.py b/Tests/LibWebView/test-webdriver-session-history.py
index a4f557932b5..eb2e9df7db7 100755
--- a/Tests/LibWebView/test-webdriver-session-history.py
+++ b/Tests/LibWebView/test-webdriver-session-history.py
@@ -90,6 +90,13 @@ class TestPageServer(http.server.ThreadingHTTPServer):
class TestPageHandler(http.server.BaseHTTPRequestHandler):
+ def end_headers(self):
+ # The tests count and block the requests that history traversals make, so each of them must reach this server.
+ # A history traversal loads a document with the "force-cache" cache mode, which uses any stored response.
+ if b"Cache-Control:" not in b"".join(getattr(self, "_headers_buffer", [])):
+ self.send_header("Cache-Control", "no-store")
+ super().end_headers()
+
def do_GET(self):
server = cast(TestPageServer, self.server)
server_port = server.server_port