Skip to content

Commit

Permalink
Improve code
Browse files Browse the repository at this point in the history
  • Loading branch information
edwinofsakh committed Jan 11, 2021
1 parent bf56e1a commit dbf3a89
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 42 deletions.
3 changes: 1 addition & 2 deletions http-monitor-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,5 @@ const cli = meow(`
}
});

httpMonitor = new HttpMonitor(cli.input[0], cli.flags);

const httpMonitor = new HttpMonitor(cli.input[0], cli.flags);
httpMonitor.start();
26 changes: 20 additions & 6 deletions http-monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const http = require('http');
const https = require('https');

const chart = require('./utils/chart');
const { DelayStatistic } = require('./utils/statistic');
const { DelayStatistics } = require('./utils/statistics');
const { ConsoleApplication } = require('./utils/console');

const LABELS = ['(-∞, 0.0)', '[0.0,0.2)', '[0.2,0.4)', '[0.4,0.6)', '[0.6,0.8)', '[0.8,1.0)', '[1.0,1.2)', '[1.2,1.4)', '[1.4,1.6)', '[1.6,1.8)', '[2.0, +∞)'];
Expand All @@ -12,7 +12,7 @@ class HttpMonitor extends ConsoleApplication {
super();

// Target url
this._target = target || 'https://network-tools.herokuapp.com/';
this._target = target || 'https://network-tools.herokuapp.com/time';

// Options
this._options = options;
Expand All @@ -21,7 +21,7 @@ class HttpMonitor extends ConsoleApplication {
this._client = this._target.includes('https') ? https : http;

// Response delay statistics
this._delay = new DelayStatistic(2000, 10, LABELS);
this._delay = new DelayStatistics(2000, 10, LABELS);

// Status text
this._text = 'Loading...\n';
Expand All @@ -34,6 +34,12 @@ class HttpMonitor extends ConsoleApplication {

// Number of failed requests
this._failed = 0;

// Task interval handler
this._taskLoop = null;

// Render interval handler
this._renderLoop = null;
}

/**
Expand All @@ -42,10 +48,18 @@ class HttpMonitor extends ConsoleApplication {
start() {
// Starts target loading cycle.
this._loadTarget();
setInterval(() => this._loadTarget(), this._options.interval);
this._taskLoop = setInterval(() => this._loadTarget(), this._options.interval);

// Starts rendering cycle.
setInterval(() => this._render(), this._spf);
this._renderLoop = setInterval(() => this._render(), this._spf);
}

/**
* Stops http monitor.
*/
stop() {
if (this._taskLoop) clearInterval(this._taskLoop);
if (this._renderLoop) clearInterval(this._renderLoop);
}

/**
Expand All @@ -66,7 +80,7 @@ class HttpMonitor extends ConsoleApplication {
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error(`Request Failed.\nStatus Code: ${statusCode}`);
} else if (!(contentType === 'application/json' || contentType === 'text/html')) {
} else if (!(contentType.indexOf('application/json') > -1 || contentType === 'text/html')) {
error = new Error(`Invalid content-type.\nExpected application/json or text/html but received ${contentType}`);
}

Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
"start": "node ping-monitor-cli.js",
"test": "mocha"
},
"bin": {
"ping-monitor": "./ping-monitor-cli.js",
"http-monitor": "./http-monitor-cli.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/edwinofsakh/ping-logger.git"
Expand Down
2 changes: 1 addition & 1 deletion ping-monitor-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ const cli = meow(`
}
});

pingMonitor = new PingMonitor(cli.input[0], cli.flags);
const pingMonitor = new PingMonitor(cli.input[0], cli.flags);
pingMonitor.start();
37 changes: 26 additions & 11 deletions ping-monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const fs = require('fs');
const path = require('path');
const ping = require('net-ping');
const csvWriter = require('csv-write-stream');
const { DelayStatistic } = require('./utils/statistic');
const { DelayStatistics } = require('./utils/statistics');
const { ConsoleApplication } = require('./utils/console');

const SUCCESS = 'Success';
Expand All @@ -16,17 +16,25 @@ class PingMonitor extends ConsoleApplication {
this._lastResponse = 'NA';

this._sent = 0;
this._delay = new DelayStatistic(200, 8);
this._delay = new DelayStatistics(200, 8);

this._statuses = {};

this._session = null;

this._filename = '';
this._writer = null;
this._stream = null;

if (this._options.save) {
this._filename = path.join('.', 'results', `ping-monitor-${this._target}-${Date.now()}.csv`);
}

// Task interval handler
this._taskLoop = null;

// Render interval handler
this._renderLoop = null;
}

/**
Expand All @@ -36,13 +44,20 @@ class PingMonitor extends ConsoleApplication {
this._printSettings();
this._initWriter();
this._initSession();

// Starts ping cycle.
this._pingTarget();
setInterval(() => this._pingTarget(), this._options.interval);
this._taskLoop = setInterval(() => this._pingTarget(), this._options.interval);

// Starts rendering cycle.
setInterval(() => this._render(), this._spf);
this._renderLoop = setInterval(() => this._render(), this._spf);
}

stop() {
if (this._taskLoop) clearInterval(this._taskLoop);
if (this._renderLoop) clearInterval(this._renderLoop);
if (this._writer) this._writer.end();
if (this._session) this._session.close();
}

/**
Expand Down Expand Up @@ -96,11 +111,11 @@ class PingMonitor extends ConsoleApplication {
* Initializes ping session.
*/
_initSession() {
this.session = ping.createSession({ timeout: this._options.timeout, retries: 0 });
this._session = ping.createSession({ timeout: this._options.timeout, retries: 0 });
this._clear();
this._log('New session was created');

this.session.on('error', (error) => {
this._session.on('error', (error) => {
this._clear();

if (error) {
Expand All @@ -109,10 +124,10 @@ class PingMonitor extends ConsoleApplication {
this._log('(Error) Unknown socket error');
}

this.session.close();
this._session.close();
});

this.session.on('close', () => {
this._session.on('close', () => {
this._clear();
this._log('Session was closed');
});
Expand All @@ -122,7 +137,7 @@ class PingMonitor extends ConsoleApplication {
* Pings target ip.
*/
_pingTarget() {
this.session.pingHost(this._target, (error, _target, sent, received) => {
this._session.pingHost(this._target, (error, _target, sent, received) => {
const ping = received - sent;
const status = error ? error.constructor.name : 'Success';
const message = error ? error.message.trim() : 'Done';
Expand Down Expand Up @@ -156,7 +171,7 @@ class PingMonitor extends ConsoleApplication {
*/
_updateStatistics(status, ping) {
this._sent++;

this._statuses[status] = (this._statuses[status] || 0) + 1;

if (status === SUCCESS) {
Expand Down
21 changes: 21 additions & 0 deletions test/http-monitor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const expect = require('chai').expect;
const HttpMonitor = require('../http-monitor');

describe('HttpMonitor', () => {
describe('constructor', () => {
it('should create monitor', () => {
const options = {
timeout: 2000,
interval: 2000,
results: false,
histogram: false,
chart: false,
fullscreen: false,
verbose: false
}

const httpMonitor = new HttpMonitor(null, options);
expect(httpMonitor).to.be.an.instanceof(HttpMonitor);
});
});
});
21 changes: 21 additions & 0 deletions test/ping-monitor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const expect = require('chai').expect;
const PingMonitor = require('../ping-monitor');

describe('PingMonitor', () => {
describe('start', () => {
it('should create monitor', () => {
const pingMonitor = new PingMonitor(null, {timeout: 2000, interval: 2000});
expect(pingMonitor).to.be.an.instanceof(PingMonitor);
});
});

describe('start', () => {
it('should create monitor', () => {
expect(() => {
const pingMonitor = new PingMonitor(null, {timeout: 2000, interval: 2000});
pingMonitor.start(() => {});
pingMonitor.stop();
}).to.not.throw();
});
});
});
16 changes: 8 additions & 8 deletions test/statistic.js → test/statistics.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
const expect = require('chai').expect;
const { Statistic } = require('../utils/statistic');
const { Statistics } = require('../utils/statistics');

describe('Statistic', () => {
describe('Statistics', () => {
describe('constructor', () => {
it('should support empty parameters', () => {
const stat = new Statistic();
const stat = new Statistics();
expect(stat.count).to.equal(0);
});

it('should support custom parameters', () => {
const stat = new Statistic(-100, 100, 10, 10);
const stat = new Statistics(-100, 100, 10, 10);
expect(stat.count).to.equal(0);
});
});

describe('update', () => {
it('should increase count', () => {
const stat = new Statistic();
const stat = new Statistics();
expect(stat.count).to.equal(0);
stat.update(1);
expect(stat.count).to.equal(1);
});

it('should change min value', () => {
const stat = new Statistic();
const stat = new Statistics();

stat.update(0);
expect(stat.min).to.equal(0);
Expand All @@ -36,7 +36,7 @@ describe('Statistic', () => {
});

it('should change max value', () => {
const stat = new Statistic();
const stat = new Statistics();

stat.update(0);
expect(stat.max).to.equal(0);
Expand All @@ -51,7 +51,7 @@ describe('Statistic', () => {

describe('text', () => {
it('should return min, avg, max', () => {
const stat = new Statistic();
const stat = new Statistics();
stat.update(0);
stat.update(1);
stat.update(2);
Expand Down
22 changes: 9 additions & 13 deletions utils/statistic.js → utils/statistics.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
const { Histogram } = require('./histogram');

class Statistic {
constructor(min, max, bins, labels) {
class Statistics {
constructor(min, max, bins, labels, size) {
// Overall statistics
this._count = 0;
this._mean = 0;
this._min = Number.POSITIVE_INFINITY;
this._max = Number.NEGATIVE_INFINITY;

this._recent = { size: 100, values: [] };
this._history = [];
this._overall = {};
this._recent = { size: size || 100, values: [] };

// Overall histogram
this._histogram = new Histogram(min, max, bins, labels);
}

update(value) {
this._history.push(value);

this._recent.values.push(value);
if (this._recent.values.length > this._recent.size) {
this._recent.values.shift();
Expand Down Expand Up @@ -55,16 +55,12 @@ class Statistic {
return this._recent.values;
}

get history() {
return this._history;
}

get histogram() {
return this._histogram;
}
}

class DelayStatistic extends Statistic {
class DelayStatistics extends Statistics {
constructor(max, k, labels) {
super(0, max, k, labels);
}
Expand All @@ -74,5 +70,5 @@ class DelayStatistic extends Statistic {
}
}

module.exports.Statistic = Statistic;
module.exports.DelayStatistic = DelayStatistic;
module.exports.Statistics = Statistics;
module.exports.DelayStatistics = DelayStatistics;

0 comments on commit dbf3a89

Please sign in to comment.