Mutex.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. /**
  3. * Copyright 2023 Google LLC.
  4. * Copyright (c) Microsoft Corporation.
  5. * Copyright 2022 The Chromium Authors.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. Object.defineProperty(exports, "__esModule", { value: true });
  20. exports.Mutex = void 0;
  21. /**
  22. * Use Mutex class to coordinate local concurrent operations.
  23. * Once `acquire` promise resolves, you hold the lock and must
  24. * call `release` function returned by `acquire` to release the
  25. * lock. Failing to `release` the lock may lead to deadlocks.
  26. */
  27. class Mutex {
  28. #locked = false;
  29. #acquirers = [];
  30. // This is FIFO.
  31. acquire() {
  32. const state = { resolved: false };
  33. if (this.#locked) {
  34. return new Promise((resolve) => {
  35. this.#acquirers.push(() => resolve(this.#release.bind(this, state)));
  36. });
  37. }
  38. this.#locked = true;
  39. return Promise.resolve(this.#release.bind(this, state));
  40. }
  41. #release(state) {
  42. if (state.resolved) {
  43. throw new Error('Cannot release more than once.');
  44. }
  45. state.resolved = true;
  46. const resolve = this.#acquirers.shift();
  47. if (!resolve) {
  48. this.#locked = false;
  49. return;
  50. }
  51. resolve();
  52. }
  53. async run(action) {
  54. const release = await this.acquire();
  55. try {
  56. // Note we need to await here because we want the await to release AFTER
  57. // that await happens. Returning action() will trigger the release
  58. // immediately which is counter to what we want.
  59. const result = await action();
  60. return result;
  61. }
  62. finally {
  63. release();
  64. }
  65. }
  66. }
  67. exports.Mutex = Mutex;
  68. //# sourceMappingURL=Mutex.js.map