Pure Javascript OCR for more than 100 Languages 📖🎉🖥
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.9 KiB

6 years ago
const createJob = require('./createJob');
const { log } = require('./utils/log');
6 years ago
const getId = require('./utils/getId');
let schedulerCounter = 0;
module.exports = () => {
6 years ago
const id = getId('Scheduler', schedulerCounter);
const workers = {};
6 years ago
const runningWorkers = {};
let jobQueue = [];
6 years ago
schedulerCounter += 1;
const getQueueLen = () => jobQueue.length;
const getNumWorkers = () => Object.keys(workers).length;
const dequeue = () => {
if (jobQueue.length !== 0) {
const wIds = Object.keys(workers);
for (let i = 0; i < wIds.length; i += 1) {
6 years ago
if (typeof runningWorkers[wIds[i]] === 'undefined') {
jobQueue[0](workers[wIds[i]]);
break;
}
}
}
};
6 years ago
const queue = (action, payload) => (
new Promise((resolve, reject) => {
6 years ago
const job = createJob({ action, payload });
6 years ago
jobQueue.push(async (w) => {
jobQueue.shift();
6 years ago
runningWorkers[w.id] = job;
6 years ago
try {
6 years ago
resolve(await w[action].apply(this, [...payload, job.id]));
6 years ago
} catch (err) {
reject(err);
} finally {
delete runningWorkers[w.id];
dequeue();
6 years ago
}
});
log(`[${id}]: Add ${job.id} to JobQueue`);
6 years ago
log(`[${id}]: JobQueue length=${jobQueue.length}`);
dequeue();
})
);
const addWorker = (w) => {
workers[w.id] = w;
log(`[${id}]: Add ${w.id}`);
log(`[${id}]: Number of workers=${getNumWorkers()}`);
6 years ago
dequeue();
return w.id;
};
6 years ago
const addJob = async (action, ...payload) => {
if (getNumWorkers() === 0) {
throw Error(`[${id}]: You need to have at least one worker before adding jobs`);
}
return queue(action, payload);
};
6 years ago
const terminate = async () => {
6 years ago
Object.keys(workers).forEach(async (wid) => {
await workers[wid].terminate();
});
jobQueue = [];
};
return {
addWorker,
addJob,
terminate,
6 years ago
getQueueLen,
getNumWorkers,
};
};