blob: 97a7ee8e096a99036d9f7b643ae1d276dc610720 [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.
17 chrome.storage.sync.onChanged.addListener(() => {
18 console.debug('[optionsWatcher] Marking options as stale.');
19 this.isStale = true;
20 });
21 }
22
23 // Returns a promise resolving to the value of option |option|.
24 getOption(option) {
25 if (!this.watchedOptions.includes(option))
26 return Promise.reject(new Error(
27 '[optionsWatcher] We\'re not watching option ' + option + '.'));
28
29 // When the cached value is marked as stale, it might be possible that there
30 // is a flood of calls to isEnabled(), which in turn causes a flood of calls
31 // to getOptions() because it takes some time for it to be marked as not
32 // stale. Thus, hiding the logic behind a mutex fixes this.
33 return this.mutex.runExclusive(() => {
34 if (!this.isStale) return Promise.resolve(this.options[option]);
35
36 return getOptions(this.watchedOptions).then(options => {
37 this.options = options;
38 this.isStale = false;
39 return this.options[option];
40 });
41 });
42 }
43
44 // Returns a promise resolving to whether the |feature| is enabled.
45 isEnabled(feature) {
46 return this.getOption(feature).then(option => option === true);
47 }
48}