ProcessingQueue.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. static LOGGER_PREFIX = `${log_js_1.LogType.debug}:queue`;
  23. #logger;
  24. #processor;
  25. #queue = [];
  26. // Flag to keep only 1 active processor.
  27. #isProcessing = false;
  28. constructor(processor, logger) {
  29. this.#processor = processor;
  30. this.#logger = logger;
  31. }
  32. add(entry, name) {
  33. this.#queue.push([entry, name]);
  34. // No need in waiting. Just initialize processor if needed.
  35. void this.#processIfNeeded();
  36. }
  37. async #processIfNeeded() {
  38. if (this.#isProcessing) {
  39. return;
  40. }
  41. this.#isProcessing = true;
  42. while (this.#queue.length > 0) {
  43. const arrayEntry = this.#queue.shift();
  44. if (!arrayEntry) {
  45. continue;
  46. }
  47. const [entryPromise, name] = arrayEntry;
  48. this.#logger?.(ProcessingQueue.LOGGER_PREFIX, 'Processing event:', name);
  49. await entryPromise
  50. .then((entry) => {
  51. if (entry.kind === 'error') {
  52. this.#logger?.(log_js_1.LogType.debugError, 'Event threw before sending:', entry.error.message, entry.error.stack);
  53. return;
  54. }
  55. return this.#processor(entry.value);
  56. })
  57. .catch((error) => {
  58. this.#logger?.(log_js_1.LogType.debugError, 'Event was not processed:', error?.message);
  59. });
  60. }
  61. this.#isProcessing = false;
  62. }
  63. }
  64. exports.ProcessingQueue = ProcessingQueue;
  65. //# sourceMappingURL=ProcessingQueue.js.map