blob: de14a8519edabcd798636e799b59ccfc4abbcbfa [file] [log] [blame]
Adrià Vilanova Martínez6e4f9c72022-01-24 23:27:11 +01001import {Mutex, withTimeout} from 'async-mutex';
2
3import {getOptions} from './optionsUtils.js';
4
5export default class OptionsWatcher {
6 constructor(options) {
7 this.watchedOptions = options;
8 this.options = [];
9 for (let o of options) this.options[o] = false;
10 this.isStale = true;
11 this.mutex = withTimeout(new Mutex(), 60 * 1000);
12
13 // If the extension settings change, set the current cached value as stale.
14 // We could try only doing this only when we're sure it has changed, but
15 // there are many factors (if the user has changed it manually, if a kill
16 // switch was activated, etc.) so we'll do it every time.
Adrià Vilanova Martínezbc4d6a32022-02-12 16:47:34 +010017 chrome.storage.onChanged.addListener((changes, areaName) => {
18 if (areaName !== 'sync') return;
Adrià Vilanova Martínez6e4f9c72022-01-24 23:27:11 +010019 console.debug('[optionsWatcher] Marking options as stale.');
20 this.isStale = true;
21 });
22 }
23
24 // Returns a promise resolving to the value of option |option|.
25 getOption(option) {
26 if (!this.watchedOptions.includes(option))
27 return Promise.reject(new Error(
28 '[optionsWatcher] We\'re not watching option ' + option + '.'));
29
30 // When the cached value is marked as stale, it might be possible that there
31 // is a flood of calls to isEnabled(), which in turn causes a flood of calls
32 // to getOptions() because it takes some time for it to be marked as not
33 // stale. Thus, hiding the logic behind a mutex fixes this.
34 return this.mutex.runExclusive(() => {
35 if (!this.isStale) return Promise.resolve(this.options[option]);
36
37 return getOptions(this.watchedOptions).then(options => {
38 this.options = options;
39 this.isStale = false;
40 return this.options[option];
41 });
42 });
43 }
44
45 // Returns a promise resolving to whether the |feature| is enabled.
46 isEnabled(feature) {
47 return this.getOption(feature).then(option => option === true);
48 }
49}