Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: neDB persistent datastore #48

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions dashboard/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ node_modules/
# Prevent test coverage reports from being added
.coverage
.nyc_output

/lib/data
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we storing the data in the project directory itself?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah right now we are. I'll move this to a config file.

4 changes: 2 additions & 2 deletions dashboard/bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ program
)
.option('-d, --daemonize', 'Run the server as a daemon.')
.option('-t, --test', 'Run the CLI without any actions for unit tests.')
.action(() => {
.action(async () => {
if (program.opts().test) {
return;
}
Expand All @@ -31,7 +31,7 @@ program
return;
}

Server.init();
await Server.init();
});

// Run this script if this is a direct stdin.
Expand Down
34 changes: 34 additions & 0 deletions dashboard/lib/controllers/batchQueue/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class BatchQueue {
constructor(queueProcessor) {
this.queue = [];
this.processing = false;
this.queueProcessor = queueProcessor;
}

add(data) {
this.queue.push(data);
this.processQueue();
}

async processQueue() {
if (this.queue.length == 0) {
this.processing = false;
return;
}

if (this.processing) return;

this.processing = true;
const currentQueue = this.queue;
this.queue = [];

await currentQueue.reduce(async (prevPromise, item) => {
await prevPromise;
await this.queueProcessor(item);
}, Promise.resolve());

return this.processQueue;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be a function call?

}
}

module.exports = BatchQueue;
91 changes: 53 additions & 38 deletions dashboard/lib/controllers/run.js
Original file line number Diff line number Diff line change
@@ -1,83 +1,98 @@
const Run = require('../models/run');
const db = require('../store');
const Event = require('../models/event');
const RunStat = require('../models/runStat');
const BatchQueue = require('./batchQueue');

const api = {
insert: async (data) => {
const runs = await db.getTable('runs');
await runs.insert(data.id, new Run(data));
},

findOne: async (id) => {
const runs = await db.getTable('runs');

if (!id) throw new TypeError('Invalid id');
return runs.findOne(id);
},
if (!data.id) throw new TypeError('Invalid run data');

find: async () => {
const runs = await db.getTable('runs');
return runs.find();
},
const runDocument = Run.create(data);
const run = await runDocument.save();

clear: async () => {
const runs = await db.getTable('runs');
return runs.clear();
if (!run)
throw new Error('Unable to save run data. Incoherent schema.');
},

pause: async (id) => {
if (!id) throw new TypeError('Invalid id');
const run = await api.findOne(id);
const run = await Run.findOne({ _id: id });

if (!run) throw new Error('Run not found.');
run.setPaused();

run.status = 'paused';
await run.save();
},

resume: async (id) => {
if (!id) throw new TypeError('Invalid id');
const run = await api.findOne(id);
const run = await Run.findOne({ _id: id });

if (!run) throw new Error('Run not found.');
run.setActive();

run.status = 'active';
await run.save();
},

abort: async (id) => {
if (!id) throw new TypeError('Invalid id');
const run = await api.findOne(id);
const run = await Run.findOne({ _id: id });

if (!run) throw new Error('Run not found.');
run.setAborted();

run.status = 'aborted';
run.endTime = Date.now();
await run.save();
},

done: async (id) => {
if (!id) throw new TypeError('Invalid id');
const run = await api.findOne(id);
const run = await Run.findOne({ _id: id });

if (!run) throw new Error('Run not found.');
run.setFinished();

if (run.status === 'aborted') return;

run.status = 'finished';
run.endTime = Date.now();
await run.save();
},

interrupt: async (id) => {
if (!id) throw new TypeError('Invalid id');
const run = await api.findOne(id);
const run = await Run.findOne({ _id: id });

if (!run) throw new Error('Run not found.');
run.setInterrupted();

run.status = 'interrupted';
await run.save();
},

addEvent: async (data) => {
if (!data.id) throw new TypeError('Invalid id');
const run = await api.findOne(data.id);
saveEvent: async (data) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make these methods (saveEvent and saveStats) private?

Copy link
Contributor Author

@elit-altum elit-altum Oct 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These methods are defined in an object and not a class, can they be private as well? 🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, just don't include them in the object. It's not using this so it doesn't need to be in the object. Just define it before the object and it should be good.

Sidenote: If it did use this, you can rename it to _saveEvent to convey the intention that it is a private method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On it @coditva, just busy with my endsems this week. Will get this done asap

if (!data.runId) throw new TypeError('Invalid parent id');

if (!run) throw new Error('Run not found.');
run.addEvent(data);
const event = Event.create(data);
if (!event) throw new Error('Invalid event type');
await event.save();
},

addStats: async (data) => {
if (!data.id) throw new TypeError('Invalid id');
const run = await api.findOne(data.id);
saveStats: async (data) => {
if (!data.runId) throw new TypeError('Invalid parent id');

if (!run) throw new Error('Run not found.');
run.addRunStats(data);
const stat = RunStat.create(data);
if (!stat) throw new Error('Invalid stat type');

await stat.save();
},

addEvent: async (data) => {
const batch = new BatchQueue(api.saveEvent);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are creating a new queue every time this function is called. Is this expected? 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, my bad. Should I initialize separate queues in this file and use them?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The queue should be initialised once. Either when the file is imported or when the first call is made.

Also, do note that:

  • If multiple actions depend on each other, they should use a single queue.
  • If actions are independent but depend on multiple calls of itself, it should use a single queue.
  • If actions are not dependent on multiple calls of itself either, it doesn't need a queue.

batch.add(data);
},

addStats: async (data) => {
const batch = new BatchQueue(api.saveStats);
batch.add(data);
},
};

Expand Down
21 changes: 11 additions & 10 deletions dashboard/lib/models/event.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
class Event {
constructor(data) {
this._init(data);
}
const Document = require('camo').Document;

class Event extends Document {
constructor() {
super();

_init(data) {
this.type = data.type;
this.parentId = data.id;
this.time = Date.now();
this.args = data.args;
this.err = data.err;
this.type = String;
this.parentId = String;
this.time = Number;
this.args = [String];
this.err = String;
this.runId = String;
}
}

Expand Down
94 changes: 18 additions & 76 deletions dashboard/lib/models/run.js
Original file line number Diff line number Diff line change
@@ -1,86 +1,28 @@
const Document = require('camo').Document;
const Event = require('./event');
const RunStat = require('./runStat');

const RUN_STATUS = {
ACTIVE: 'active',
PAUSED: 'paused',
FINISHED: 'finished',
ABORTED: 'aborted',
INTERRUPTED: 'interrupted',
};
class Run extends Document {
constructor() {
super();

class Run {
constructor(data) {
this._init(data);
this.command = String;
this._id = String;
this.startTime = Date;
this.endTime = {
type: Date,
default: 0,
};
this.status = String;
}

_init(data) {
this.command = data.command;
this.id = data.id;

this.startTime = data.startTime;
this.endTime = 0;

this.events = [];
this.cpuUsage = [];
this.memoryUsage = [];
}

// setters
setPaused() {
this.status = RUN_STATUS.PAUSED;
}

setFinished() {
if (this.isAborted()) return;

this.status = RUN_STATUS.FINISHED;
this.endTime = Date.now();
}

setActive() {
this.status = RUN_STATUS.ACTIVE;
}

setAborted() {
this.status = RUN_STATUS.ABORTED;
this.endTime = Date.now();
}

setInterrupted() {
this.status = RUN_STATUS.INTERRUPTED;
}

addEvent(data) {
if (data.err) this.setInterrupted();
this.events.push(new Event(data));
}

addRunStats(data) {
data.cpu &&
data.memory &&
this.cpuUsage.push(data.cpu) &&
this.memoryUsage.push(data.memory);
}

// getters
isPaused() {
return this.status === RUN_STATUS.PAUSED;
}

isFinished() {
return this.status === RUN_STATUS.FINISHED;
}

isActive() {
return this.status === RUN_STATUS.ACTIVE;
}

isAborted() {
return this.status === RUN_STATUS.ABORTED;
async populate() {
this.stats = await RunStat.find({ runId: this._id });
this.events = await Event.find({ runId: this._id }, { sort: 'time' });
}

isInterrupted() {
return this.status === RUN_STATUS.INTERRUPTED;
static collectionName() {
return 'runs';
}
}

Expand Down
13 changes: 13 additions & 0 deletions dashboard/lib/models/runStat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const Document = require('camo').Document;

class RunStat extends Document {
constructor() {
super();

this.cpu = Number;
this.memory = Number;
this.runId = String;
}
}

module.exports = RunStat;
25 changes: 12 additions & 13 deletions dashboard/lib/store/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
const Table = require('./table');
const connect = require('camo').connect;
const paths = require('env-paths')('newman-dashboard');
const uri = `nedb://${paths.data}`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be in config file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we create a separate PR for config files?


const cache = {};
const init = async () => {
try {
await connect(uri);

const api = {
_createTable: (tableName) => {
cache[tableName] = new Table({});
return;
},

getTable: async (tableName) => {
if (!cache.hasOwnProperty(tableName)) api._createTable(tableName);
return cache[tableName];
},
// cleanup function to terminate db connection
return () => process.exit(0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cleanup function would terminate the whole process! Shouldn't we only close the connection?

} catch (e) {
console.log('Error in connecting to database.');
}
};

module.exports = api;
module.exports = { init };
28 changes: 0 additions & 28 deletions dashboard/lib/store/table/index.js

This file was deleted.

Loading