|
1 | 1 | 'use strict'
|
2 | 2 |
|
| 3 | +const promisify = require('promisify-es6') |
| 4 | +const Big = require('big.js') |
| 5 | +const Pushable = require('pull-pushable') |
| 6 | +const human = require('human-to-milliseconds') |
| 7 | +const toStream = require('pull-stream-to-stream') |
| 8 | + |
| 9 | +function bandwidthStats (self, opts) { |
| 10 | + return new Promise((resolve, reject) => { |
| 11 | + let stats |
| 12 | + |
| 13 | + if (opts.peer) { |
| 14 | + stats = self._libp2pNode.stats.forPeer(opts.peer) |
| 15 | + } else if (opts.proto) { |
| 16 | + stats = self._libp2pNode.stats.forProtocol(opts.proto) |
| 17 | + } else { |
| 18 | + stats = self._libp2pNode.stats.global |
| 19 | + } |
| 20 | + |
| 21 | + if (!stats) { |
| 22 | + resolve({ |
| 23 | + totalIn: new Big(0), |
| 24 | + totalOut: new Big(0), |
| 25 | + rateIn: new Big(0), |
| 26 | + rateOut: new Big(0) |
| 27 | + }) |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + resolve({ |
| 32 | + totalIn: stats.snapshot.dataReceived, |
| 33 | + totalOut: stats.snapshot.dataSent, |
| 34 | + rateIn: new Big(stats.movingAverages.dataReceived['60000'].movingAverage() / 60), |
| 35 | + rateOut: new Big(stats.movingAverages.dataSent['60000'].movingAverage() / 60) |
| 36 | + }) |
| 37 | + }) |
| 38 | +} |
| 39 | + |
3 | 40 | module.exports = function stats (self) {
|
| 41 | + const _bwPullStream = (opts) => { |
| 42 | + opts = opts || {} |
| 43 | + let interval = null |
| 44 | + let stream = Pushable(true, () => { |
| 45 | + if (interval) { |
| 46 | + clearInterval(interval) |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + if (opts.poll) { |
| 51 | + human(opts.interval || '1s', (err, value) => { |
| 52 | + if (err) throw err |
| 53 | + |
| 54 | + interval = setInterval(() => { |
| 55 | + bandwidthStats(self, opts) |
| 56 | + .then((stats) => stream.push(stats)) |
| 57 | + .catch((err) => stream.end(err)) |
| 58 | + }, value) |
| 59 | + }) |
| 60 | + } else { |
| 61 | + bandwidthStats(self, opts) |
| 62 | + .then((stats) => { |
| 63 | + stream.push(stats) |
| 64 | + stream.end() |
| 65 | + }) |
| 66 | + .catch((err) => stream.end(err)) |
| 67 | + } |
| 68 | + |
| 69 | + return stream.source |
| 70 | + } |
| 71 | + |
4 | 72 | return {
|
5 | 73 | bitswap: require('./bitswap')(self).stat,
|
6 |
| - repo: require('./repo')(self).stat |
| 74 | + repo: require('./repo')(self).stat, |
| 75 | + bw: promisify((opts, callback) => { |
| 76 | + if (typeof opts === 'function') { |
| 77 | + callback = opts |
| 78 | + opts = {} |
| 79 | + } |
| 80 | + |
| 81 | + bandwidthStats(self, opts) |
| 82 | + .then((stats) => callback(null, stats)) |
| 83 | + .catch((err) => callback(err)) |
| 84 | + }), |
| 85 | + bwReadableStream: (opts) => toStream.source(_bwPullStream(opts)), |
| 86 | + bwPullStream: _bwPullStream |
7 | 87 | }
|
8 | 88 | }
|
0 commit comments