Adrià Vilanova Martínez | 6e4f9c7 | 2022-01-24 23:27:11 +0100 | [diff] [blame] | 1 | import {Mutex, withTimeout} from 'async-mutex'; |
| 2 | |
| 3 | import {getOptions} from './optionsUtils.js'; |
| 4 | |
| 5 | export 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ínez | bc4d6a3 | 2022-02-12 16:47:34 +0100 | [diff] [blame] | 17 | chrome.storage.onChanged.addListener((changes, areaName) => { |
| 18 | if (areaName !== 'sync') return; |
Adrià Vilanova Martínez | 6e4f9c7 | 2022-01-24 23:27:11 +0100 | [diff] [blame] | 19 | 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 | } |