@tripod311/leg5
Version:
Zero-dependency concurrent function execution for Node.js using worker threads.
92 lines (91 loc) • 2.96 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const thread_1 = __importDefault(require("./thread"));
const task_1 = __importDefault(require("./task"));
class Leg5 {
constructor() {
this.pool_size = 4;
this.task_timeout = 0;
this.abort_timeout = 1000;
this.threads = [];
this.task_map = new Map();
this.queue = [];
}
setup(options) {
if (options) {
if (options.pool_size) {
this.pool_size = options.pool_size;
}
if (options.task_timeout) {
this.task_timeout = options.task_timeout;
}
if (options.abort_timeout) {
this.abort_timeout = options.abort_timeout;
}
}
for (let i = 0; i < this.pool_size; i++) {
this.threads.push(new thread_1.default(i, this.abort_timeout, this.pull_from_queue.bind(this)));
}
}
shutdown() {
for (let i = 0; i < this.threads.length; i++) {
this.threads[i].shutdown();
}
this.threads = [];
}
async register_task(name, path, argsList) {
if (this.task_map.has(name)) {
throw new Error(`Task ${name} is already registered`);
}
if (path.startsWith("code:")) {
this.task_map.set(name, {
script: path.slice(5),
argsList: argsList
});
}
else {
const code = await fs_1.default.promises.readFile(path, "utf-8");
this.task_map.set(name, {
script: code,
argsList: argsList
});
}
}
unregister_task(name) {
this.task_map.delete(name);
for (let i = 0; i < this.threads.length; i++) {
this.threads[i].forget_task(name);
}
}
has_task(name) {
return this.task_map.has(name);
}
run_task(name, args, override_timeout) {
const taskDescription = this.task_map.get(name);
if (taskDescription !== undefined) {
const task = new task_1.default(name, taskDescription.script, taskDescription.argsList, args || {}, override_timeout || this.task_timeout);
let freeThread = this.threads.find(t => !t.isBusy);
if (freeThread !== undefined) {
freeThread.run(task);
}
else {
this.queue.push(task);
}
return task;
}
else {
throw new Error(`Task ${name} not found`);
}
}
pull_from_queue(id) {
if (this.queue.length > 0) {
const task = this.queue.shift();
this.threads[id].run(task);
}
}
}
exports.default = Leg5;