From 95f8ae3d3ca3732a4c0d7aef4fc674343b6e433b Mon Sep 17 00:00:00 2001 From: MKPLKN <15703708+MKPLKN@users.noreply.github.com> Date: Wed, 4 Sep 2024 19:34:38 +0300 Subject: [PATCH] Use speedometer --- lib/monitor.js | 27 +++++++++++---------------- package.json | 1 + 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/lib/monitor.js b/lib/monitor.js index f6c2711..8deb36c 100644 --- a/lib/monitor.js +++ b/lib/monitor.js @@ -1,4 +1,5 @@ const ReadyResource = require('ready-resource') +const speedometer = require('speedometer') const debounce = require('debounceify') module.exports = class Monitor extends ReadyResource { @@ -8,6 +9,7 @@ module.exports = class Monitor extends ReadyResource { this.blobs = null this.name = opts.name this.entry = opts.entry + this.speed = speedometer() this._boundOnAppend = debounce(this._onAppend.bind(this)) this._boundOnUpload = this._onUpload.bind(this) @@ -18,12 +20,12 @@ module.exports = class Monitor extends ReadyResource { startTime: 0, percentage: 0, peersCount: 0, - speed: null, - blocks: null, - totalBytes: null, // local + bytes loaded during monitoring - monitoringBytes: null, // bytes loaded during monitoring - targetBytes: null, - targetBlocks: null + speed: 0, + blocks: 0, + totalBytes: 0, // local + bytes loaded during monitoring + monitoringBytes: 0, // bytes loaded during monitoring + targetBytes: 0, + targetBlocks: 0 } // Updated on each upload/download event @@ -80,23 +82,16 @@ module.exports = class Monitor extends ReadyResource { if (!this.entry || this.closing) return if (!isWithinRange(index, this.entry)) return + if (!stats.startTime) stats.startTime = Date.now() stats.peersCount = from.replicator.peers.length stats.blocks++ stats.monitoringBytes += bytes stats.totalBytes += bytes + stats.speed = this.speed(bytes) + stats.percentage = Number(((stats.totalBytes / stats.targetBytes) * 100).toFixed(2)) - this._calculateStats(stats) this.emit('update') } - - _calculateStats (stats) { - if (!stats.startTime) stats.startTime = Date.now() - stats.percentage = Number(((stats.totalBytes / stats.targetBytes) * 100).toFixed(2)) - const timeElapsed = (Date.now() - stats.startTime) / 1000 - if (timeElapsed > 0) { - stats.speed = Math.floor(stats.monitoringBytes / timeElapsed) // bytes/sec - } - } } function isWithinRange (index, entry) { diff --git a/package.json b/package.json index 193e241..0ae8eb3 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "mirror-drive": "^1.2.0", "ready-resource": "^1.0.0", "safety-catch": "^1.0.2", + "speedometer": "^1.1.0", "streamx": "^2.12.4", "sub-encoder": "^2.1.1", "unix-path-resolve": "^1.0.2"