Skip to content

Commit

Permalink
Use speedometer
Browse files Browse the repository at this point in the history
  • Loading branch information
MKPLKN committed Sep 4, 2024
1 parent ca5af17 commit 8e85746
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
28 changes: 12 additions & 16 deletions lib/monitor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const ReadyResource = require('ready-resource')
const speedometer = require('speedometer')
const debounce = require('debounceify')

module.exports = class Monitor extends ReadyResource {
Expand All @@ -8,6 +9,7 @@ module.exports = class Monitor extends ReadyResource {
this.blobs = null
this.name = opts.name
this.entry = opts.entry
this.speed = null

this._boundOnAppend = debounce(this._onAppend.bind(this))
this._boundOnUpload = this._onUpload.bind(this)
Expand All @@ -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
Expand Down Expand Up @@ -80,23 +82,17 @@ 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()
if (!this.speed) this.speed = speedometer()
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) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit 8e85746

Please sign in to comment.