Skip to content

Commit 0942a8a

Browse files
committed
Parallel sync/async for best effort policy fetching under any circumstance.
1 parent b0a870c commit 0942a8a

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

src/bg/main.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@
212212

213213
function onSyncMessage(msg, sender) {
214214
switch(msg.id) {
215-
case "fetchPolicy":
215+
case "fetchChildPolicy":
216216
return messageHandler.fetchChildPolicy(msg, sender);
217217
break;
218218
}

src/content/staticNS.js

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,21 +90,44 @@
9090
// extra hops to ensure that scripts don't run when CSP has not been set through HTTP headers
9191
this.syncFetchPolicy();
9292
} else {
93-
let msg = {id: "fetchPolicy", url, contextUrl: url};
94-
debug(`Synchronously fetching policy for ${url}.`);
95-
let policy = browser.runtime.sendSyncMessage(msg);
96-
if (!policy) {
97-
debug(`Couldn't retrieve policy synchronously, trying async.`);
98-
(async () => this.setup(await browser.runtime.sendMessage(msg)))();
99-
} else {
93+
let msg = {id: "fetchChildPolicy", url, contextUrl: url};
94+
95+
let asyncFetch = (async () => {
96+
let policy = null;
97+
for (let attempts = 10; !(policy || this.policy) && attempts-- > 0;) {
98+
try {
99+
debug(`Retrieving policy asynchronously (${attempts} attempts left).`);
100+
policy = await Messages.send(msg.id, msg) || this.domPolicy;
101+
debug("Asynchronous policy", policy);
102+
} catch (e) {
103+
error(e, "(Asynchronous policy fetch)");
104+
}
105+
}
100106
this.setup(policy);
101-
}
107+
});
108+
debug(`Synchronously fetching policy for ${url}.`);
109+
let policy = null;
110+
let attempts = 100;
111+
let refetch = () => {
112+
policy = browser.runtime.sendSyncMessage(msg) || this.domPolicy;
113+
if (policy) {
114+
this.setup(policy);
115+
} else if (attempts-- > 0) {
116+
debug(`Couldn't retrieve policy synchronously (${attempts} attempts left).`);
117+
if (asyncFetch) {
118+
asyncFetch();
119+
asyncFetch = null;
120+
}
121+
queueMicrotask(refetch);
122+
}
123+
};
124+
refetch();
102125
}
103126
},
104127

105128
setup(policy) {
106129
if (this.policy) return false;
107-
debug("%s, %s, fetched %o", document.URL, document.readyState, policy);
130+
debug("%s, %s, fetched %o", document.URL, document.readyState, policy, new Error().stack); // DEV_ONLY
108131
if (!policy) {
109132
policy = {permissions: {capabilities: []}, localFallback: true};
110133
}

0 commit comments

Comments
 (0)