Skip to content

Commit

Permalink
fix(options): decouple observe from options (#2003)
Browse files Browse the repository at this point in the history
  • Loading branch information
smalluban authored Oct 30, 2024
1 parent b8a3f0c commit 78533f0
Show file tree
Hide file tree
Showing 16 changed files with 255 additions and 224 deletions.
76 changes: 41 additions & 35 deletions src/background/adblocker.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ import {
} from '@ghostery/adblocker-webextension';
import { parse } from 'tldts-experimental';

import Options, { observe, ENGINES, isPaused } from '/store/options.js';
import Options, { ENGINES, isPaused } from '/store/options.js';

import * as engines from '/utils/engines.js';
import * as trackerdb from '/utils/trackerdb.js';
import * as OptionsObserver from '/utils/options-observer.js';
import Request from '/utils/request.js';
import asyncSetup from '/utils/setup.js';
import { debugMode } from '/utils/debug.js';
Expand Down Expand Up @@ -124,41 +125,46 @@ async function updateEngines() {

const HOUR_IN_MS = 60 * 60 * 1000;
export const setup = asyncSetup([
observe(async (value, lastValue) => {
options = value;

const enabledEngines = getEnabledEngines(value);
const prevEnabledEngines = lastValue && getEnabledEngines(lastValue);

if (
// Reload/mismatched main engine
!(await engines.init(engines.MAIN_ENGINE)) ||
// Enabled engines changed
(prevEnabledEngines &&
(enabledEngines.length !== prevEnabledEngines.length ||
enabledEngines.some((id, i) => id !== prevEnabledEngines[i])))
) {
// The regional filters engine is no longer used, so we must remove it
// from the storage. We do it as rarely as possible, to avoid unnecessary loads.
// TODO: this can be removed in the future release when most of the users will have
// the new version of the extension
engines.remove('regional-filters');

await reloadMainEngine();
}

if (options.filtersUpdatedAt < Date.now() - HOUR_IN_MS) {
await updateEngines();
}
}),
observe('experimentalFilters', async (value, lastValue) => {
engines.setEnv('env_experimental', value);
OptionsObserver.addListener(
async function adblockerEngines(value, lastValue) {
options = value;

const enabledEngines = getEnabledEngines(value);
const prevEnabledEngines = lastValue && getEnabledEngines(lastValue);

if (
// Reload/mismatched main engine
!(await engines.init(engines.MAIN_ENGINE)) ||
// Enabled engines changed
(prevEnabledEngines &&
(enabledEngines.length !== prevEnabledEngines.length ||
enabledEngines.some((id, i) => id !== prevEnabledEngines[i])))
) {
// The regional filters engine is no longer used, so we must remove it
// from the storage. We do it as rarely as possible, to avoid unnecessary loads.
// TODO: this can be removed in the future release when most of the users will have
// the new version of the extension
engines.remove('regional-filters');

await reloadMainEngine();
}

// Experimental filters changed to enabled
if (lastValue !== undefined && value) {
await updateEngines();
}
}),
if (options.filtersUpdatedAt < Date.now() - HOUR_IN_MS) {
await updateEngines();
}
},
),
OptionsObserver.addListener(
'experimentalFilters',
async (value, lastValue) => {
engines.setEnv('env_experimental', value);

// Experimental filters changed to enabled
if (lastValue !== undefined && value) {
await updateEngines();
}
},
),
]);

function adblockerInjectStylesWebExtension(
Expand Down
11 changes: 8 additions & 3 deletions src/background/custom-filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ import {
createOffscreenConverter,
} from '/utils/dnr-converter.js';
import * as engines from '/utils/engines.js';
import * as OptionsObserver from '/utils/options-observer.js';

import Options, { observe } from '/store/options.js';
import Options from '/store/options.js';
import CustomFilters from '/store/custom-filters.js';

import { setup } from '/background/adblocker.js';
Expand Down Expand Up @@ -209,7 +210,9 @@ async function update(text, { trustedScriptlets }) {
return result;
}

observe('customFilters', async ({ enabled, trustedScriptlets }, lastValue) => {
OptionsObserver.addListener('customFilters', async (value, lastValue) => {
const { enabled, trustedScriptlets } = value;

// Background startup
if (!lastValue) {
// If custom filters are disabled, we don't care if engine was reloaded
Expand All @@ -218,7 +221,9 @@ observe('customFilters', async ({ enabled, trustedScriptlets }, lastValue) => {

// If we cannot initialize engine, we need to update it
if (!(await engines.init(engines.CUSTOM_ENGINE))) {
update((await store.resolve(CustomFilters)).text, { trustedScriptlets });
update((await store.resolve(CustomFilters)).text, {
trustedScriptlets,
});
}
} else {
// If only trustedScriptlets has changed, we don't update automatically.
Expand Down
5 changes: 3 additions & 2 deletions src/background/dnr.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/

import { observe, ENGINES, isPaused } from '/store/options.js';
import { ENGINES, isPaused } from '/store/options.js';
import * as OptionsObserver from '/utils/options-observer.js';

if (__PLATFORM__ === 'chromium' || __PLATFORM__ === 'safari') {
const DNR_RESOURCES = chrome.runtime
Expand All @@ -20,7 +21,7 @@ if (__PLATFORM__ === 'chromium' || __PLATFORM__ === 'safari') {
// Ensure that DNR rulesets are equal to those from options.
// eg. when web extension updates, the rulesets are reset
// to the value from the manifest.
observe(async (options) => {
OptionsObserver.addListener(async function dnr(options) {
const globalPause = isPaused(options);

const ids = ENGINES.map(({ name, key }) => {
Expand Down
4 changes: 2 additions & 2 deletions src/background/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/

import { idleOptionsObservers } from '/store/options.js';
import * as OptionsObserver from '/utils/options-observer.js';

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
switch (msg.action) {
Expand All @@ -35,7 +35,7 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
break;
// This is used only by the e2e tests to detect idle state
case 'idleOptionsObservers': {
idleOptionsObservers.then(() => {
OptionsObserver.waitForIdle().then(() => {
sendResponse('done');
console.info('[helpers] "idleOptionsObservers" response...');
});
Expand Down
2 changes: 1 addition & 1 deletion src/background/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import './serp.js';
import './helpers.js';
import './external.js';

import './telemetry/index.js';
import './reporting/index.js';
import './telemetry/index.js';

import './devtools.js';
4 changes: 2 additions & 2 deletions src/background/onboarding.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/
import { observe } from '/store/options.js';
import * as OptionsObserver from '/utils/options-observer.js';

observe('onboarding', (onboarding) => {
OptionsObserver.addListener('onboarding', (onboarding) => {
if (!onboarding.shown) {
chrome.tabs.create({
url: chrome.runtime.getURL('/pages/onboarding/index.html'),
Expand Down
10 changes: 6 additions & 4 deletions src/background/paused.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
*/

import { store } from 'hybrids';
import Options, { observe, GLOBAL_PAUSE_ID } from '/store/options.js';

import Options, { GLOBAL_PAUSE_ID } from '/store/options.js';
import * as OptionsObserver from '/utils/options-observer.js';

// Pause / unpause hostnames
const PAUSED_ALARM_PREFIX = 'options:revoke';
Expand All @@ -33,7 +35,7 @@ const ALL_RESOURCE_TYPES = [
'other',
];

observe('paused', async (paused, prevPaused) => {
OptionsObserver.addListener('paused', async (paused, prevPaused) => {
const alarms = (await chrome.alarms.getAll()).filter(({ name }) =>
name.startsWith(PAUSED_ALARM_PREFIX),
);
Expand Down Expand Up @@ -127,12 +129,12 @@ observe('paused', async (paused, prevPaused) => {
],
removeRuleIds,
});
console.log('DNR: pause rules updated');
console.log('[dnr] pause rules updated');
} else if (removeRuleIds.length) {
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds,
});
console.log('DNR: pause rules updated');
console.log('[dnr] pause rules updated');
}
}
});
Expand Down
6 changes: 3 additions & 3 deletions src/background/reporting/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import './webrequest-monkey-patch.js';

import { setLogLevel, describeLoggers } from '@whotracksme/reporting/reporting';

import { observe } from '/store/options.js';

import asyncSetup from '/utils/setup.js';
import debug from '/utils/debug.js';
import * as OptionsObserver from '/utils/options-observer.js';

import config from './config.js';
import communication from './communication.js';
import urlReporter from './url-reporter.js';
Expand All @@ -40,7 +40,7 @@ import webRequestReporter from './webrequest-reporter.js';
})();

const setup = asyncSetup([
observe('terms', async (terms) => {
OptionsObserver.addListener('terms', async function reporting(terms) {
if (terms) {
await urlReporter.init().catch((e) => {
console.warn(
Expand Down
5 changes: 3 additions & 2 deletions src/background/reporting/webrequest-reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ import {
} from '@whotracksme/reporting/reporting';

import getBrowserInfo from '/utils/browser-info.js';
import { observe, isPaused } from '/store/options.js';
import { isPaused } from '/store/options.js';
import Request from '/utils/request.js';
import * as OptionsObserver from '/utils/options-observer.js';

import { updateTabStats } from '../stats.js';

Expand All @@ -33,7 +34,7 @@ if (__PLATFORM__ === 'chromium' || __PLATFORM__ === 'firefox') {
webRequestPipeline.init();

let options = {};
observe((value) => {
OptionsObserver.addListener(function webRequestReporting(value) {
options = value;
});

Expand Down
5 changes: 3 additions & 2 deletions src/background/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import { getOffscreenImageData } from '/ui/wheel.js';
import { order } from '/ui/categories.js';

import DailyStats from '/store/daily-stats.js';
import Options, { isPaused, observe } from '/store/options.js';
import Options, { isPaused } from '/store/options.js';

import { isSerpSupported } from '/utils/opera.js';
import * as OptionsObserver from '/utils/options-observer.js';

import AutoSyncingMap from '/utils/map.js';
import { getMetadata, getUnidentifiedTracker } from '/utils/trackerdb.js';
Expand All @@ -40,7 +41,7 @@ function setBadgeColor(color = '#3f4146' /* gray-600 */) {
chromeAction.setBadgeBackgroundColor({ color });
}

observe('terms', async (terms) => {
OptionsObserver.addListener('terms', async function stats(terms) {
if (!terms) {
await chromeAction.setBadgeText({ text: '!' });
setBadgeColor('#f13436' /* danger-500 */);
Expand Down
Loading

0 comments on commit 78533f0

Please sign in to comment.