[FIX] website_event_track: only cache local & cdn based urls

This commit allows to filter out the requests to local-ish domains (cf.
the current host and an optionally configured CDN for the current
website) and preventing from cluttering the cache used by the
ServiceWorker with tracking files, scripts or other non-necessary
assets.

This allows to even further reduce the possible "opaque" requests from
being stored in the cache (as they use way more space than regular/basic
responses).

X-original-commit: 052bc7665e89426fb51928e43bd4a15dbf6cb705
This commit is contained in:
Pierre Paridans
2020-10-02 13:56:32 +00:00
parent 0e56f7ce7d
commit dc95d43efb
2 changed files with 16 additions and 1 deletions
@@ -48,8 +48,13 @@ class TrackManifest(http.Controller):
""" Returns a ServiceWorker javascript file scoped for website_event
"""
sw_file = get_module_resource('website_event_track', 'static/src/js/service_worker.js')
with open(sw_file, 'rb') as fp:
with open(sw_file, 'r') as fp:
body = fp.read()
js_cdn_url = 'undefined'
if request.website.cdn_activated:
cdn_url = request.website.cdn_url.replace('"','%22').replace('\x5c','%5C')
js_cdn_url = '"%s"' % cdn_url
body = body.replace('__ODOO_CDN_URL__', js_cdn_url)
response = request.make_response(body, [
('Content-Type', 'text/javascript'),
('Service-Worker-Allowed', url_for('/event')),
@@ -5,6 +5,7 @@ const SYNCABLE_ROUTES = ["/event/track/toggle_reminder"];
const CACHABLE_ROUTES = ["/web/webclient/version_info"];
const MAX_CACHE_SIZE = 512 * 1024 * 1024; // 500 MB
const MAX_CACHE_QUOTA = 0.5;
const CDN_URL = __ODOO_CDN_URL__; // {string|undefined} the cdn_url configured for the website if activated
const { Store, set, get, del } = idbKeyval;
const pendingRequestsQueueName = `${PREFIX}-pending-requests`;
@@ -12,6 +13,8 @@ const cacheName = `${PREFIX}-cache`;
const syncStore = new Store(`${PREFIX}-sync-db`, `${PREFIX}-sync-store`);
const cacheStore = new Store(`${PREFIX}-cache-db`, `${PREFIX}-cache-store`);
const offlineRoute = `${self.registration.scope}/offline`;
const scopeURL = new URL(self.registration.scope);
const cdnURL = CDN_URL ? (CDN_URL.startsWith("http") ? new URL(CDN_URL) : new URL(`http:${CDN_URL}`)) : undefined;
/**
*
@@ -147,6 +150,13 @@ const buildEmptyResponse = () => new Response(JSON.stringify({ jsonrpc: "2.0", i
* @returns {Promise}
*/
const cacheRequest = async (request, response) => {
// only attempts to cache local or cdn delivered urls
const url = new URL(request.url);
if (url.hostname !== scopeURL.hostname && (!cdnURL || url.hostname !== cdnURL.hostname)) {
console.error(`ignoring cache for ${request.url} => ${url.hostname}, local: ${scopeURL.hostname}, cdn: ${cdnURL ? cdnURL.hostname : cdnURL}`);
return;
}
// don't even attempt to cache:
// - error pages (why cache that?)
// - non-"basic" response types, which include tracker 1-time opaque requests