ProgressTracker.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ProgressTracker = void 0;
  4. /**
  5. * Tracks progress of one socket data transfer at a time.
  6. */
  7. class ProgressTracker {
  8. constructor() {
  9. this.bytesOverall = 0;
  10. this.intervalMs = 500;
  11. this.onStop = noop;
  12. this.onHandle = noop;
  13. }
  14. /**
  15. * Register a new handler for progress info. Use `undefined` to disable reporting.
  16. */
  17. reportTo(onHandle = noop) {
  18. this.onHandle = onHandle;
  19. }
  20. /**
  21. * Start tracking transfer progress of a socket.
  22. *
  23. * @param socket The socket to observe.
  24. * @param name A name associated with this progress tracking, e.g. a filename.
  25. * @param type The type of the transfer, typically "upload" or "download".
  26. */
  27. start(socket, name, type) {
  28. let lastBytes = 0;
  29. this.onStop = poll(this.intervalMs, () => {
  30. const bytes = socket.bytesRead + socket.bytesWritten;
  31. this.bytesOverall += bytes - lastBytes;
  32. lastBytes = bytes;
  33. this.onHandle({
  34. name,
  35. type,
  36. bytes,
  37. bytesOverall: this.bytesOverall
  38. });
  39. });
  40. }
  41. /**
  42. * Stop tracking transfer progress.
  43. */
  44. stop() {
  45. this.onStop(false);
  46. }
  47. /**
  48. * Call the progress handler one more time, then stop tracking.
  49. */
  50. updateAndStop() {
  51. this.onStop(true);
  52. }
  53. }
  54. exports.ProgressTracker = ProgressTracker;
  55. /**
  56. * Starts calling a callback function at a regular interval. The first call will go out
  57. * immediately. The function returns a function to stop the polling.
  58. */
  59. function poll(intervalMs, updateFunc) {
  60. const id = setInterval(updateFunc, intervalMs);
  61. const stopFunc = (stopWithUpdate) => {
  62. clearInterval(id);
  63. if (stopWithUpdate) {
  64. updateFunc();
  65. }
  66. // Prevent repeated calls to stop calling handler.
  67. updateFunc = noop;
  68. };
  69. updateFunc();
  70. return stopFunc;
  71. }
  72. function noop() { }