1. /**
  2. * Rate Limited Time Value Exporter
  3. *
  4. * Exports time values with rate limiting to prevent abuse.
  5. *
  6. * @param {Function} timeValueGenerator - A function that generates the time value.
  7. * @param {number} rateLimit - The maximum number of exports allowed per time unit (e.g., 10 exports per second).
  8. * @param {number} timeUnit - The time unit for the rate limit (e.g., 1000 for milliseconds).
  9. * @returns {Generator} A generator that yields time values with rate limiting.
  10. */
  11. function* rateLimitedTimeExporter(timeValueGenerator, rateLimit, timeUnit) {
  12. let queue = []; // Queue of time values to be exported.
  13. let running = 0; // Number of exports currently in progress.
  14. let lastExportTime = 0; // Timestamp of the last export.
  15. async function exportTimeValue() {
  16. if (queue.length > 0 && running < rateLimit) {
  17. const timeValue = queue.shift();
  18. running++;
  19. const now = Date.now();
  20. if (now - lastExportTime >= timeUnit) {
  21. lastExportTime = now;
  22. }
  23. console.log("Exporting time value:", timeValue);
  24. running--;
  25. yield timeValue;
  26. // Schedule the next export.
  27. setTimeout(exportTimeValue, 0); // Use setTimeout(..., 0) for minimal delay
  28. }
  29. }
  30. // Add the time values to the queue.
  31. const timeValues = timeValueGenerator();
  32. for (const timeValue of timeValues) {
  33. queue.push(timeValue);
  34. }
  35. // Start the export process.
  36. await exportTimeValue();
  37. }
  38. export default rateLimitedTimeExporter;

Add your comment