blob: 261a6d4f380f5fd6f5de6510b1eb84e0bd5e8538 [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
Adrià Vilanova Martínezf7e86852024-05-11 14:16:38 +02005/**
6 * @deprecated Use {@link OptionsProvider} instead.
7 */
Adrià Vilanova Martínez8300cc42024-05-11 12:42:52 +02008export default class PartialOptionsWatcher {
Adrià Vilanova Martínez6e4f9c72022-01-24 23:27:11 +01009 constructor(options) {
10 this.watchedOptions = options;
11 this.options = [];
12 for (let o of options) this.options[o] = false;
13 this.isStale = true;
14 this.mutex = withTimeout(new Mutex(), 60 * 1000);
15
16 // If the extension settings change, set the current cached value as stale.
17 // We could try only doing this only when we're sure it has changed, but
18 // there are many factors (if the user has changed it manually, if a kill
19 // switch was activated, etc.) so we'll do it every time.
Adrià Vilanova Martínezbc4d6a32022-02-12 16:47:34 +010020 chrome.storage.onChanged.addListener((changes, areaName) => {
21 if (areaName !== 'sync') return;
Adrià Vilanova Martínez6e4f9c72022-01-24 23:27:11 +010022 console.debug('[optionsWatcher] Marking options as stale.');
23 this.isStale = true;
24 });
25 }
26
27 // Returns a promise resolving to the value of option |option|.
28 getOption(option) {
29 if (!this.watchedOptions.includes(option))
30 return Promise.reject(new Error(
31 '[optionsWatcher] We\'re not watching option ' + option + '.'));
32
33 // When the cached value is marked as stale, it might be possible that there
34 // is a flood of calls to isEnabled(), which in turn causes a flood of calls
35 // to getOptions() because it takes some time for it to be marked as not
36 // stale. Thus, hiding the logic behind a mutex fixes this.
37 return this.mutex.runExclusive(() => {
38 if (!this.isStale) return Promise.resolve(this.options[option]);
39
40 return getOptions(this.watchedOptions).then(options => {
41 this.options = options;
42 this.isStale = false;
43 return this.options[option];
44 });
45 });
46 }
47
48 // Returns a promise resolving to whether the |feature| is enabled.
49 isEnabled(feature) {
50 return this.getOption(feature).then(option => option === true);
51 }
52}