Skip to content

Commit

Permalink
Updates modules for two space indentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
qubyte committed Sep 16, 2017
1 parent 371f5f1 commit 1fb1aac
Show file tree
Hide file tree
Showing 8 changed files with 566 additions and 566 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
indent_size = 2
trim_trailing_whitespace = true
22 changes: 11 additions & 11 deletions examples/persistence/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,26 @@ const rb = new Rubidium();

// Load the persisted queue when redis is ready.
redis.hgetall('rubidium-queue').then(stringifiedJobs => {
for (const uuid of Object.keys(stringifiedJobs)) {
// Add the persisted jobs to the queue, taking care to silence them so
// they are not duplicated in redis.
rb.add(JSON.parse(stringifiedJobs[uuid]), true);
}
for (const uuid of Object.keys(stringifiedJobs)) {
// Add the persisted jobs to the queue, taking care to silence them so
// they are not duplicated in redis.
rb.add(JSON.parse(stringifiedJobs[uuid]), true);
}
});

rb.on('addJob', job => {
redis.hset('rubidium-queue', job.uuid, JSON.stringify(job)).then(() => {
console.log(`Job ${job.uuid} persisted.`);
});
redis.hset('rubidium-queue', job.uuid, JSON.stringify(job)).then(() => {
console.log(`Job ${job.uuid} persisted.`);
});
});

rb.on('job', job => {
redis.hdel('rubidium-queue', job.uuid);
console.log(`Job ${job.uuid} emitted, message: ${job.message}`);
redis.hdel('rubidium-queue', job.uuid);
console.log(`Job ${job.uuid} emitted, message: ${job.message}`);
});

rb.on('removeJob', job => {
redis.hdel('rubidium-queue', job.uuid);
redis.hdel('rubidium-queue', job.uuid);
});

rb.add({ time: Date.now() + 10000, message: '10 seconds have passed.' });
46 changes: 23 additions & 23 deletions examples/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ const rb = new Rubidium();
// callback in the message with the message itself as the body. Requests have
// a custom header so that registered jobs can't create another job.
rb.on('job', job => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'FROM-ATD-SERVER': 'true' },
body: JSON.stringify(job.message)
};

return fetch(job.message.callbackUrl, options)
.catch(err => console.error(err.stack || err.message));
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'FROM-ATD-SERVER': 'true' },
body: JSON.stringify(job.message)
};

return fetch(job.message.callbackUrl, options)
.catch(err => console.error(err.stack || err.message));
});

// Create a router for the Toisu! server.
Expand All @@ -30,36 +30,36 @@ const router = new Router();
// This middleware will use the :timestamp parameter and the request body to
// create a job, and then add it to the rubidium instance.
function addJobMiddleware(req, res) {
const params = this.get('params');
const time = parseInt(params.timestamp, 10);
const message = this.get('body');
const params = this.get('params');
const time = parseInt(params.timestamp, 10);
const message = this.get('body');

// Stop callbacks registering new jobs.
if (req.headers['FROM-ATD-SERVER'] !== 'true') {
rb.add({ time, message });
}
// Stop callbacks registering new jobs.
if (req.headers['FROM-ATD-SERVER'] !== 'true') {
rb.add({ time, message });
}

res.statusCode = 202;
res.end();
res.statusCode = 202;
res.end();
}

// Use this to accept requests from itself as a test.
function testMiddleware(req, res) {
const message = this.get('body');
const message = this.get('body');

console.log('Received callback request:', message);
console.log('Received callback request:', message);

res.statusCode = 204;
res.end();
res.statusCode = 204;
res.end();
}

// Give the router the JSON body parsing middleware and the add job middleware.
router.route('/add/:timestamp', {
post: [body.json(), addJobMiddleware]
post: [body.json(), addJobMiddleware]
});

router.route('/test', {
post: [body.json(), testMiddleware]
post: [body.json(), testMiddleware]
});

// Create a Toisu! instance.
Expand Down
28 changes: 14 additions & 14 deletions lib/Job.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import uuid from './uuidv4';

export default class Job {
constructor(spec) {
if (!spec) {
throw new Error('Spec must be an object');
}
constructor(spec) {
if (!spec) {
throw new Error('Spec must be an object');
}

if (spec.message === undefined) {
throw new Error('Message argument must be populated.');
}
if (spec.message === undefined) {
throw new Error('Message argument must be populated.');
}

this.time = spec.time instanceof Date ? spec.time.getTime() : parseInt(spec.time, 10);
this.time = spec.time instanceof Date ? spec.time.getTime() : parseInt(spec.time, 10);

if (!this.time) {
throw new TypeError('Time must be a Date object or an integer.');
}
if (!this.time) {
throw new TypeError('Time must be a Date object or an integer.');
}

this.message = spec.message;
this.message = spec.message;

this.uuid = spec.uuid || uuid();
}
this.uuid = spec.uuid || uuid();
}
}
134 changes: 67 additions & 67 deletions lib/Rubidium.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,108 +5,108 @@ const jobs = new WeakMap();
const timeouts = new WeakMap();

function getJobFromQueue(queue, uuid) {
for (let i = 0, len = queue.length; i < len; i++) {
if (queue[i].uuid === uuid) {
return queue[i];
}
for (let i = 0, len = queue.length; i < len; i++) {
if (queue[i].uuid === uuid) {
return queue[i];
}
}
}

function makeTimeout(rb, queue) {
clearTimeout(timeouts.get(rb));
clearTimeout(timeouts.get(rb));

if (!queue.length) {
return timeouts.set(rb, null);
}
if (!queue.length) {
return timeouts.set(rb, null);
}

// setTimeout accepts 32bit integers for the time value. If the next job is
// later than this, we'll set a shorter timeout as a waypoint.
const dt = Math.min(Math.max(queue[0].time - Date.now(), 0), 2147483647);
// setTimeout accepts 32bit integers for the time value. If the next job is
// later than this, we'll set a shorter timeout as a waypoint.
const dt = Math.min(Math.max(queue[0].time - Date.now(), 0), 2147483647);

timeouts.set(rb, setTimeout(() => {
while (queue.length && queue[0].time <= Date.now()) {
rb.emit('job', queue.shift());
}
timeouts.set(rb, setTimeout(() => {
while (queue.length && queue[0].time <= Date.now()) {
rb.emit('job', queue.shift());
}

makeTimeout(rb, queue);
}, dt));
makeTimeout(rb, queue);
}, dt));
}

export default class Rubidium extends EventEmitter {
constructor() {
super();

jobs.set(this, []);

timeouts.set(this, null);
}
constructor() {
super();

add(spec, silent) {
const queue = jobs.get(this);
const job = new Job(spec);
jobs.set(this, []);

queue.push(job);
queue.sort((a, b) => a.time - b.time);
timeouts.set(this, null);
}

if (!silent) {
this.emit('addJob', job);
}
add(spec, silent) {
const queue = jobs.get(this);
const job = new Job(spec);

if (job === queue[0]) {
makeTimeout(this, queue);
}
queue.push(job);
queue.sort((a, b) => a.time - b.time);

return job;
if (!silent) {
this.emit('addJob', job);
}

find(uuid) {
return getJobFromQueue(jobs.get(this), uuid);
if (job === queue[0]) {
makeTimeout(this, queue);
}

remove(uuid, silent) {
const queue = jobs.get(this);
const job = getJobFromQueue(queue, uuid);
return job;
}

if (!job) {
return;
}
find(uuid) {
return getJobFromQueue(jobs.get(this), uuid);
}

const index = queue.indexOf(job);
remove(uuid, silent) {
const queue = jobs.get(this);
const job = getJobFromQueue(queue, uuid);

queue.splice(index, 1);
if (!job) {
return;
}

if (!silent) {
this.emit('removeJob', job);
}
const index = queue.indexOf(job);

if (index === 0) {
makeTimeout(this, queue);
}
queue.splice(index, 1);

return job;
if (!silent) {
this.emit('removeJob', job);
}

clear(silent) {
const newJobs = [];
if (index === 0) {
makeTimeout(this, queue);
}

makeTimeout(this, newJobs);
return job;
}

const oldJobs = jobs.get(this);
clear(silent) {
const newJobs = [];

jobs.set(this, newJobs);
makeTimeout(this, newJobs);

if (silent) {
return;
}
const oldJobs = jobs.get(this);

for (let i = 0, len = oldJobs.length; i < len; i++) {
this.emit('removeJob', oldJobs[i]);
}
jobs.set(this, newJobs);

this.emit('clearJobs');
if (silent) {
return;
}

get hasPendingJobs() {
return jobs.get(this).length !== 0;
for (let i = 0, len = oldJobs.length; i < len; i++) {
this.emit('removeJob', oldJobs[i]);
}

this.emit('clearJobs');
}

get hasPendingJobs() {
return jobs.get(this).length !== 0;
}
}
18 changes: 9 additions & 9 deletions lib/uuidv4.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
function randomHexByte() {
const hexByte = Math.floor(Math.random() * 256).toString(16);
const hexByte = Math.floor(Math.random() * 256).toString(16);

return hexByte.length === 2 ? hexByte : '0' + hexByte;
return hexByte.length === 2 ? hexByte : `0${hexByte}`;
}

function bytes(num) {
let randomHex = '';
let randomHex = '';

for (let i = 0; i < num; i++) {
randomHex += randomHexByte();
}
for (let i = 0; i < num; i++) {
randomHex += randomHexByte();
}

return randomHex;
return randomHex;
}

function special() {
return ['8', '9', 'a', 'b'][Math.floor(Math.random() * 4)];
return ['8', '9', 'a', 'b'][Math.floor(Math.random() * 4)];
}

export default function uuidv4() {
return `${bytes(4)}-${bytes(2)}-4${bytes(3)}-${special()}${bytes(3)}-${bytes(6)}`;
return `${bytes(4)}-${bytes(2)}-4${bytes(3)}-${special()}${bytes(3)}-${bytes(6)}`;
}
Loading

0 comments on commit 1fb1aac

Please sign in to comment.