processingQueue.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. /**
  3. * Copyright 2022 Google LLC.
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. exports.ProcessingQueue = void 0;
  20. const log_js_1 = require("./log.js");
  21. class ProcessingQueue {
  22. #logger;
  23. #processor;
  24. #queue = [];
  25. // Flag to keep only 1 active processor.
  26. #isProcessing = false;
  27. constructor(processor, logger) {
  28. this.#processor = processor;
  29. this.#logger = logger;
  30. }
  31. add(entry) {
  32. this.#queue.push(entry);
  33. // No need in waiting. Just initialise processor if needed.
  34. void this.#processIfNeeded();
  35. }
  36. async #processIfNeeded() {
  37. if (this.#isProcessing) {
  38. return;
  39. }
  40. this.#isProcessing = true;
  41. while (this.#queue.length > 0) {
  42. const entryPromise = this.#queue.shift();
  43. if (entryPromise !== undefined) {
  44. await entryPromise
  45. .then((entry) => this.#processor(entry))
  46. .catch((e) => {
  47. this.#logger?.(log_js_1.LogType.system, 'Event was not processed:', e);
  48. });
  49. }
  50. }
  51. this.#isProcessing = false;
  52. }
  53. }
  54. exports.ProcessingQueue = ProcessingQueue;
  55. //# sourceMappingURL=processingQueue.js.map