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 | |
Adrià Vilanova Martínez | f7e8685 | 2024-05-11 14:16:38 +0200 | [diff] [blame] | 5 | /** |
| 6 | * @deprecated Use {@link OptionsProvider} instead. |
| 7 | */ |
Adrià Vilanova Martínez | 8300cc4 | 2024-05-11 12:42:52 +0200 | [diff] [blame] | 8 | export default class PartialOptionsWatcher { |
Adrià Vilanova Martínez | 6e4f9c7 | 2022-01-24 23:27:11 +0100 | [diff] [blame] | 9 | 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ínez | bc4d6a3 | 2022-02-12 16:47:34 +0100 | [diff] [blame] | 20 | chrome.storage.onChanged.addListener((changes, areaName) => { |
| 21 | if (areaName !== 'sync') return; |
Adrià Vilanova Martínez | 6e4f9c7 | 2022-01-24 23:27:11 +0100 | [diff] [blame] | 22 | 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 | } |