56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
|
import { v4 } from "uuid";
|
||
|
import doExec from "./internal-exec.js";
|
||
|
|
||
|
export default class JobManager {
|
||
|
constructor(clientMaxJobs) {
|
||
|
this.clientMaxJobs = clientMaxJobs;
|
||
|
this.clients = {};
|
||
|
}
|
||
|
|
||
|
getJob(clientId, jobId) {
|
||
|
return this.clients[clientId].jobs.find((j) => j.id === jobId);
|
||
|
}
|
||
|
|
||
|
getJobById(jobId) {
|
||
|
for (var client of Object.values(this.clients)) {
|
||
|
const job = client.jobs.find((j) => j.id === jobId);
|
||
|
if (!job) continue;
|
||
|
return job;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pushLog(jobId, log) {
|
||
|
const job = this.getJobById(jobId);
|
||
|
if (log instanceof Array) job.log.push(...log);
|
||
|
else job.log.push(log);
|
||
|
}
|
||
|
|
||
|
closeJob(jobId, exitcode) {
|
||
|
const job = this.getJobById(jobId);
|
||
|
job.exitcode = exitcode;
|
||
|
}
|
||
|
|
||
|
newJob(jobRequest, id) {
|
||
|
if (!jobRequest) throw Error("Request Must Be Object!");
|
||
|
if (!this.clients[id]) this.clients[id] = { jobs: [] };
|
||
|
const client = this.clients[id];
|
||
|
if (
|
||
|
client.jobs.filter((j) => j.exitcode === undefined).length >=
|
||
|
this.clientMaxJobs
|
||
|
)
|
||
|
throw Error("Client's Active Jobs Exceeded!");
|
||
|
const job = { ...jobRequest };
|
||
|
job.id = v4();
|
||
|
job.log = [];
|
||
|
this.clients[id].jobs.push(job);
|
||
|
if (process.env.INTERNAL_EXECUTOR === "true") doExec(job);
|
||
|
return { ...job };
|
||
|
}
|
||
|
|
||
|
removeJob(clientId, id) {
|
||
|
this.clients[clientId].jobs = this.clients[clientId].jobs.filter(
|
||
|
(j) => j.id !== id
|
||
|
);
|
||
|
}
|
||
|
}
|