Less logs, no betterStack, get rid of API fixes, setTimeout each API CB

This commit is contained in:
Ilya Ig. Petrov 2017-02-05 17:06:30 +00:00
parent fda42ee307
commit a460ed85d2
10 changed files with 53 additions and 87 deletions

View File

@ -35,17 +35,14 @@
}, },
checkChromeError(betterStack) { checkChromeError() {
// Chrome API calls your cb in a context different from the point of API // Chrome API calls your cb in a context different from the point of API
// method invokation. // method invokation.
const err = chrome.runtime.lastError || chrome.extension.lastError; let err = chrome.runtime.lastError || chrome.extension.lastError;
if (err) { if (err) {
const args = ['API returned error:', err]; err = new Error(err.message); // Add stack.
if (betterStack) { console.warn('API returned error:', err);
args.push('\n' + betterStack);
}
console.warn(...args);
} }
return err; return err;
@ -53,14 +50,13 @@
chromified(cb = self.mandatory(), ...replaceArgs) { chromified(cb = self.mandatory(), ...replaceArgs) {
const stack = (new Error()).stack; // Take error first callback and convert it to chrome API callback.
// Take error first callback and convert it to chrome api callback.
return function(...args) { return function(...args) {
if (replaceArgs.length) { if (replaceArgs.length) {
args = replaceArgs; args = replaceArgs;
} }
const err = self.checkChromeError(stack); const err = self.checkChromeError();
// setTimeout fixes error context. // setTimeout fixes error context.
setTimeout( cb.bind(null, err, ...args), 0 ); setTimeout( cb.bind(null, err, ...args), 0 );

View File

@ -2,6 +2,8 @@
{ // Private namespace { // Private namespace
const chromified = window.utils.chromified;
function errorJsonReplacer(key, value) { function errorJsonReplacer(key, value) {
// fooWindow.ErrorEvent !== barWindow.ErrorEvent // fooWindow.ErrorEvent !== barWindow.ErrorEvent
@ -63,7 +65,7 @@
state: window.utils.createStorage('handlers-'), state: window.utils.createStorage('handlers-'),
viewErrorVoid(type = window.utils.mandatory(), err) { viewError(type = window.utils.mandatory(), err) {
let errors = {}; let errors = {};
if (err) { if (err) {
@ -90,7 +92,7 @@
}, },
switchVoid(onOffStr, eventName) { switch(onOffStr, eventName) {
if (!['on', 'off'].includes(onOffStr)) { if (!['on', 'off'].includes(onOffStr)) {
throw new TypeError('First argument bust be "on" or "off".'); throw new TypeError('First argument bust be "on" or "off".');
@ -136,7 +138,7 @@
idToError: {}, idToError: {},
mayNotifyVoid( mayNotify(
id, title, errOrMessage, id, title, errOrMessage,
{ {
icon = 'default-128.png', icon = 'default-128.png',
@ -166,12 +168,12 @@
}, },
installListenersOnAsync(win, name, cb) { installListenersOn(win, name, cb) {
win.addEventListener('error', (errEvent) => { win.addEventListener('error', (errEvent) => {
console.warn(name + ':GLOBAL ERROR', errEvent); console.warn(name + ':GLOBAL ERROR', errEvent);
this.mayNotifyVoid('ext-error', 'Ошибка расширения', errEvent, this.mayNotify('ext-error', 'Ошибка расширения', errEvent,
{icon: 'ext-error-128.png'}); {icon: 'ext-error-128.png'});
}); });
@ -186,7 +188,8 @@
}); });
if (cb) { if (cb) {
// setTimeout changes error context. // In most cases getBackgroundPage( (bg) => installListenersOn
// Without setTimeout errors are swallowed, bug #357568
setTimeout(cb, 0); setTimeout(cb, 0);
} }
@ -201,10 +204,10 @@
chrome.proxy.settings.get( chrome.proxy.settings.get(
{}, {},
(details) => handlers.isControllable(details) chromified((err, details) => handlers.isControllable(details))
); );
chrome.notifications.onClicked.addListener( function(notId) { chrome.notifications.onClicked.addListener( chromified( (_, notId) => {
chrome.notifications.clear(notId); chrome.notifications.clear(notId);
if(notId === 'no-control') { if(notId === 'no-control') {
@ -212,13 +215,13 @@
window.utils.messages.searchSettingsForUrl('proxy') window.utils.messages.searchSettingsForUrl('proxy')
); );
} }
handlers.viewErrorVoid(notId); handlers.viewError(notId);
}); }));
handlers.installListenersOnAsync(window, 'BG'); handlers.installListenersOn(window, 'BG');
chrome.proxy.onProxyError.addListener((details) => { chrome.proxy.onProxyError.addListener( chromified( (_, details) => {
if (!handlers.ifControlled) { if (!handlers.ifControlled) {
return; return;
@ -231,19 +234,19 @@
*/ */
console.warn('PAC ERROR', details); console.warn('PAC ERROR', details);
// TOOD: add "view pac script at this line" button. // TOOD: add "view pac script at this line" button.
handlers.mayNotifyVoid('pac-error', 'Ошибка PAC!', handlers.mayNotify('pac-error', 'Ошибка PAC!',
details.error + '\n' + details.details, details.error + '\n' + details.details,
{icon: 'pac-error-128.png'} {icon: 'pac-error-128.png'}
); );
}); }));
chrome.proxy.settings.onChange.addListener((details) => { chrome.proxy.settings.onChange.addListener( chromified((_, details) => {
console.log('Proxy settings changed.', details); console.log('Proxy settings changed.', details);
const noCon = 'no-control'; const noCon = 'no-control';
if ( !handlers.isControllable(details) ) { if ( !handlers.isControllable(details) ) {
handlers.mayNotifyVoid( handlers.mayNotify(
noCon, noCon,
chrome.i18n.getMessage('noControl'), chrome.i18n.getMessage('noControl'),
chrome.i18n.getMessage('which'), chrome.i18n.getMessage('which'),
@ -253,6 +256,6 @@
chrome.notifications.clear( noCon ); chrome.notifications.clear( noCon );
} }
}); }));
} }

View File

@ -48,7 +48,7 @@
clarifyThen: function(message, cb = mandatory()) { clarifyThen: function(message, cb = mandatory()) {
return (err, ...args) => cb( clarify(err, message), ...args ); return (err, ...args) => cb( self.clarify(err, message), ...args );
}, },

View File

@ -213,7 +213,6 @@
console.log('Purging old IPs for', hostStr); console.log('Purging old IPs for', hostStr);
for(const ip of Object.keys(privates._ipToHostObj)) { for(const ip of Object.keys(privates._ipToHostObj)) {
if (hostStr === privates._ipToHostObj[ip].host) { if (hostStr === privates._ipToHostObj[ip].host) {
console.log('del', ip);
delete privates._ipToHostObj[ip]; delete privates._ipToHostObj[ip];
} }
} }
@ -230,9 +229,7 @@
// Object may be shared, string can't. // Object may be shared, string can't.
const hostObj = _getHostObj(hostStr); const hostObj = _getHostObj(hostStr);
for(const ip of ips) { for(const ip of ips) {
console.log('IP', ip);
privates._ipToHostObj[ip] = hostObj; privates._ipToHostObj[ip] = hostObj;
console.log(privates._ipToHostObj[ip], privates._ipToHostObj);
} }
} }
return cb(err, null, ...warns); return cb(err, null, ...warns);

View File

@ -102,8 +102,7 @@
constructor(mods = {}) { constructor(mods = {}) {
const defaults = getDefaults(); const defaults = getDefaults();
const ifAllDefaults = const ifAllDefaults = Object.keys(defaults)
Object.keys(defaults)
.every( .every(
(prop) => !(prop in mods) (prop) => !(prop in mods)
|| Boolean(defaults[prop]) === Boolean(mods[prop]) || Boolean(defaults[prop]) === Boolean(mods[prop])
@ -257,7 +256,7 @@
details details
? resolve(details) ? resolve(details)
: chrome.proxy.settings.get({}, resolve) : chrome.proxy.settings.get({}, chromified( (_, res) => resolve(res)))
).then( (details) => { ).then( (details) => {
@ -284,7 +283,7 @@
}, },
checkIncontinenceVoid(details) { checkIncontinence(details) {
if ( kitchenState(ifIncontinence) ) { if ( kitchenState(ifIncontinence) ) {
this._tryNowAsync(details, () => {/* Swallow. */}); this._tryNowAsync(details, () => {/* Swallow. */});
@ -295,7 +294,7 @@
keepCookedNowAsync(pacMods = mandatory(), cb = throwIfError) { keepCookedNowAsync(pacMods = mandatory(), cb = throwIfError) {
console.log('Keep cooked now...', cb); console.log('Keep cooked now...', pacMods);
if (typeof(pacMods) === 'function') { if (typeof(pacMods) === 'function') {
cb = pacMods; cb = pacMods;
pacMods = this.getCurrentConfigs(); pacMods = this.getCurrentConfigs();
@ -364,7 +363,11 @@
}; };
pacKitchen.checkIncontinenceVoid(); pacKitchen.checkIncontinence();
chrome.proxy.settings.onChange.addListener( pacKitchen.checkIncontinenceVoid.bind(pacKitchen) ); chrome.proxy.settings.onChange.addListener(
chromified(
(_, details) => pacKitchen.checkIncontinence(details)
)
);
} // Private namespace ends. } // Private namespace ends.

View File

@ -24,7 +24,6 @@
const mandatory = window.utils.mandatory; const mandatory = window.utils.mandatory;
const throwIfError = window.utils.throwIfError; const throwIfError = window.utils.throwIfError;
const chromified = window.utils.chromified; const chromified = window.utils.chromified;
const checkChromeError = window.utils.checkChromeError;
const clarifyThen = window.apis.errorsLib.clarifyThen; const clarifyThen = window.apis.errorsLib.clarifyThen;
const Warning = window.apis.errorsLib.Warning; const Warning = window.apis.errorsLib.Warning;
@ -60,13 +59,12 @@
}, },
}; };
console.log('Setting chrome proxy settings...'); console.log('Setting chrome proxy settings...');
chrome.proxy.settings.set( {value: config}, () => { chrome.proxy.settings.set( {value: config}, chromified((err) => {
const err = checkChromeError();
if (err) { if (err) {
return cb(err); return cb(err);
} }
chrome.proxy.settings.get({}, (details) => { chrome.proxy.settings.get({}, chromified((_, details) => {
if ( !window.utils.areSettingsControlledFor( details ) ) { if ( !window.utils.areSettingsControlledFor( details ) ) {
@ -78,9 +76,9 @@
} }
console.log('Successfuly set PAC in proxy settings..'); console.log('Successfuly set PAC in proxy settings..');
cb(); cb();
}); }));
}); }));
}; };
@ -397,16 +395,15 @@
chrome.alarms.clearAll( chrome.alarms.clearAll(
() => chrome.proxy.settings.clear( () => chrome.proxy.settings.clear(
{}, {},
() => { chromified((err) => {
const err = checkChromeError();
if (err) { if (err) {
return cb(err); return cb(err);
} }
this.setCurrentPacProviderKey(null); this.setCurrentPacProviderKey(null);
this.pushToStorageAsync(cb); this.pushToStorageAsync(cb);
} })
) )
); );
@ -415,9 +412,8 @@
}; };
// ON EACH LAUNCH, STARTUP, RELOAD, UPDATE, ENABLE // ON EACH LAUNCH, STARTUP, RELOAD, UPDATE, ENABLE
chrome.storage.local.get(null, (oldStorage) => { chrome.storage.local.get(null, chromified( (err, oldStorage) => {
const err = checkChromeError();
if (err) { if (err) {
throw err; throw err;
} }
@ -431,7 +427,7 @@
const antiCensorRu = window.apis.antiCensorRu; const antiCensorRu = window.apis.antiCensorRu;
chrome.alarms.onAlarm.addListener( chrome.alarms.onAlarm.addListener(
(alarm) => { chromified((_, alarm) => {
if (alarm.name === antiCensorRu._periodicUpdateAlarmReason) { if (alarm.name === antiCensorRu._periodicUpdateAlarmReason) {
console.log( console.log(
@ -441,7 +437,7 @@
antiCensorRu.syncWithPacProviderAsync(() => {/* swallow */}); antiCensorRu.syncWithPacProviderAsync(() => {/* swallow */});
} }
} })
); );
console.log('Alarm listener installed. We won\'t miss any PAC update.'); console.log('Alarm listener installed. We won\'t miss any PAC update.');
@ -533,6 +529,6 @@
* Add storage.lastPacUpdateStamp. * Add storage.lastPacUpdateStamp.
**/ **/
}); }));
} }

View File

@ -1,27 +0,0 @@
'use strict';
/* `setTimeout` changes context of execution from other window
(e.g. popup) to background window, so we may catch errors
in bg error handlers.
More: https://bugs.chromium.org/p/chromium/issues/detail?id=357568
setTimeout is applied to Async/Void methods
only (name ends with Async/Void)
*/
// Fix error context of methods of all APIs.
for(const apiName of Object.keys(window.apis)) {
const api = window.apis[apiName];
for(const prop of Object.keys(api)) {
const method = api[prop];
if ( !(
typeof(api[prop]) === 'function'
&& ['Async', 'Void'].some( (suff) => method.name.endsWith(suff) )
)
) {
continue;
}
api[prop] = function(...args) {
setTimeout(method.bind(this, ...args), 0);
};
}
}

View File

@ -31,7 +31,6 @@
"14-ip-to-host-api.js", "14-ip-to-host-api.js",
"15-pac-kitchen-api.js", "15-pac-kitchen-api.js",
"17-sync-pac-script-with-pac-provider-api.js", "17-sync-pac-script-with-pac-provider-api.js",
"20-api-fixes.js",
"30-block-informer.js", "30-block-informer.js",
"40-context-menus.js" "40-context-menus.js"
] ]

View File

@ -10,7 +10,7 @@ document.getElementById('pac-mods').onchange = function() {
}; };
chrome.runtime.getBackgroundPage( (backgroundPage) => chrome.runtime.getBackgroundPage( (backgroundPage) =>
backgroundPage.apis.errorHandlers.installListenersOnAsync( backgroundPage.apis.errorHandlers.installListenersOn(
window, 'PUP', async() => { window, 'PUP', async() => {
const getStatus = () => document.querySelector('#status'); const getStatus = () => document.querySelector('#status');
@ -119,7 +119,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
if (err) { if (err) {
getStatus().querySelector('.link-button').onclick = function() { getStatus().querySelector('.link-button').onclick = function() {
errorHandlers.viewErrorVoid('pup-ext-err', err); errorHandlers.viewError('pup-ext-err', err);
return false; return false;
}; };
@ -144,7 +144,6 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
warns = warns.filter( (w) => w ); warns = warns.filter( (w) => w );
if (err || warns.length) { if (err || warns.length) {
backgroundPage.console.log('ERR', err, 'W', warns.length, 'w', warns);
showErrors(err, ...warns); showErrors(err, ...warns);
} else { } else {
setStatusTo(afterStatus); setStatusTo(afterStatus);
@ -479,7 +478,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
conduct( conduct(
'Применяем исключения...', 'Применяем исключения...',
(cb) => pacKitchen.keepCookedNowAsync(pacMods, cb), (cb) => pacKitchen.keepCookedNowAsync(pacMods, cb),
'Исключения применены.', 'Исключения применены. Не забывайте о кэше!',
() => { () => {
excList.childNodes.forEach( excList.childNodes.forEach(
@ -616,7 +615,7 @@ HTTPS 11.22.33.44:8080;">${conf.value || localStorage.getItem(uiRaw) || ''}</tex
box.onclick = function() { box.onclick = function() {
const id = this.id.replace('if-on-', ''); const id = this.id.replace('if-on-', '');
return backgroundPage.apis.errorHandlers.switchVoid( return backgroundPage.apis.errorHandlers.switch(
this.checked ? 'on' : 'off', this.checked ? 'on' : 'off',
id id
); );

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
chrome.runtime.getBackgroundPage( (backgroundPage) => chrome.runtime.getBackgroundPage( (backgroundPage) =>
backgroundPage.apis.errorHandlers.installListenersOnAsync( backgroundPage.apis.errorHandlers.installListenersOn(
window, 'TRBL', () => { window, 'TRBL', () => {
document.getElementById('reset-settings').onclick = () => { document.getElementById('reset-settings').onclick = () => {
@ -12,7 +12,7 @@ chrome.runtime.getBackgroundPage( (backgroundPage) =>
}; };
document.getElementById('view-errors').onclick = () => document.getElementById('view-errors').onclick = () =>
backgroundPage.apis.errorHandlers.viewErrorVoid('all'); backgroundPage.apis.errorHandlers.viewError('all');
}) })
); );