| 1 | /** |
| 2 | * A simple mutex class to prevent concurrent updates. |
| 3 | */ |
| 4 | export class SimpleMutex { |
| 5 | /** |
| 6 | * @type {boolean} |
| 7 | */ |
| 8 | isBusy = false; |
| 9 | |
| 10 | /** |
| 11 | * @type {Function} |
| 12 | */ |
| 13 | callback = () => {}; |
| 14 | |
| 15 | /** |
| 16 | * Constructs a SimpleMutex. |
| 17 | * @param {Function} callback Callback function. |
| 18 | */ |
| 19 | constructor(callback) { |
| 20 | this.isBusy = false; |
| 21 | this.callback = callback; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Updates the mutex by calling the callback if not busy. |
| 26 | * @param {...any} args Callback args |
| 27 | * @returns {Promise<void>} |
| 28 | */ |
| 29 | async update(...args) { |
| 30 | // Don't touch me I'm busy... |
| 31 | if (this.isBusy) { |
| 32 | return; |
| 33 | } |
| 34 | |
| 35 | // I'm free. Let's update! |
| 36 | try { |
| 37 | this.isBusy = true; |
| 38 | await this.callback(...args); |
| 39 | } finally { |
| 40 | this.isBusy = false; |
| 41 | } |
| 42 | } |
| 43 | } |