Fix heuristic to verify whether a resource on a remote server is stale

Related discussion:
https://github.com/uBlockOrigin/uBlock-issues/discussions/3022
This commit is contained in:
Raymond Hill 2023-12-14 16:51:28 -05:00
parent 7822db1304
commit a2caa7da78
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
1 changed files with 11 additions and 29 deletions

View File

@ -95,31 +95,11 @@ const extractMetadataFromList = (content, fields) => {
assets.extractMetadataFromList = extractMetadataFromList; assets.extractMetadataFromList = extractMetadataFromList;
const resourceTimeFromXhr = xhr => { const resourceTimeFromXhr = xhr => {
try { if ( typeof xhr.response !== 'string' ) { return 0; }
// First lookup timestamp from content
let assetTime = 0;
if ( typeof xhr.response === 'string' ) {
const metadata = extractMetadataFromList(xhr.response, [ const metadata = extractMetadataFromList(xhr.response, [
'Last-Modified' 'Last-Modified'
]); ]);
assetTime = metadata.lastModified || 0; return metadata.lastModified || 0;
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Age
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date
let networkTime = 0;
if ( assetTime === 0 ) {
const age = parseInt(xhr.getResponseHeader('Age'), 10);
if ( isNaN(age) === false ) {
const time = (new Date(xhr.getResponseHeader('Date'))).getTime();
if ( isNaN(time) === false ) {
networkTime = time - age * 1000;
}
}
}
return Math.max(assetTime, networkTime, 0);
} catch(_) {
}
return 0;
}; };
const resourceTimeFromParts = (parts, time) => { const resourceTimeFromParts = (parts, time) => {
@ -216,14 +196,14 @@ const getContentURLs = (assetKey, options = {}) => {
return 0; return 0;
}); });
} }
if ( Array.isArray(entry.cdnURLs) ) { if ( options.favorOrigin !== true && Array.isArray(entry.cdnURLs) ) {
const cdnURLs = entry.cdnURLs.slice(); const cdnURLs = entry.cdnURLs.slice();
for ( let i = 0, n = cdnURLs.length; i < n; i++ ) { for ( let i = 0, n = cdnURLs.length; i < n; i++ ) {
const j = Math.floor(Math.random() * n); const j = Math.floor(Math.random() * n);
if ( j === i ) { continue; } if ( j === i ) { continue; }
[ cdnURLs[j], cdnURLs[i] ] = [ cdnURLs[i], cdnURLs[j] ]; [ cdnURLs[j], cdnURLs[i] ] = [ cdnURLs[i], cdnURLs[j] ];
} }
if ( options.favorLocal || options.favorOrigin ) { if ( options.favorLocal ) {
contentURLs.push(...cdnURLs); contentURLs.push(...cdnURLs);
} else { } else {
contentURLs.unshift(...cdnURLs); contentURLs.unshift(...cdnURLs);
@ -1068,8 +1048,10 @@ async function getRemote(assetKey, options = {}) {
error = undefined; error = undefined;
// If fetched resource is older than cached one, ignore // If fetched resource is older than cached one, ignore
if ( options.favorOrigin !== true ) {
stale = resourceIsStale(result, cacheDetails); stale = resourceIsStale(result, cacheDetails);
if ( stale ) { continue; } if ( stale ) { continue; }
}
// Success // Success
assetCacheWrite(assetKey, { assetCacheWrite(assetKey, {