123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249 |
- import JobContext from "@/JobContext";
- import JobStatistics from "@/JobStatistics";
- import LogBook, { Log } from "@/LogBook";
- import ModuleManager from "@/ModuleManager";
- import { JobOptions } from "@/types/JobOptions";
- import { Modules } from "@/types/Modules";
- export enum JobStatus {
- QUEUED = "QUEUED",
- ACTIVE = "ACTIVE",
- PAUSED = "PAUSED",
- COMPLETED = "COMPLETED"
- }
- export default class Job {
- private _name: string;
- private _module: Modules[keyof Modules];
- private _jobFunction: any;
- private _payload: any;
- private _context: JobContext;
- private _priority: number;
- private _longJob?: {
- title: string;
- progress?: {
- data: unknown;
- time: Date;
- timeout?: NodeJS.Timeout;
- };
- };
- private _uuid: string;
- private _status: JobStatus;
- private _createdAt: number;
- private _startedAt?: number;
- private _completedAt?: number;
-
- public constructor(
- name: string,
- moduleName: keyof Modules,
- payload: any,
- options?: Omit<JobOptions, "runDirectly">
- ) {
- this._name = name;
- this._priority = 1;
- const module = ModuleManager.getModule(moduleName);
- if (!module) throw new Error("Module not found.");
- this._module = module;
- this._jobFunction = this._module.getJob(this._name).method;
- this._payload = payload;
- JobStatistics.updateStats(this.getName(), "added");
- let contextOptions;
- if (options) {
- const { priority, longJob, session, socketId } = options;
- if (session || socketId) contextOptions = { session, socketId };
- if (priority) this._priority = priority;
- if (longJob)
- this._longJob = {
- title: longJob
- };
- }
- this._context = new JobContext(this, contextOptions);
-
- this._uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
- /[xy]/g,
- c => {
- const r = (Math.random() * 16) | 0;
- const v = c == "x" ? r : (r & 0x3) | 0x8;
- return v.toString(16);
- }
- );
- this._status = JobStatus.QUEUED;
- this._createdAt = performance.now();
- }
-
- public getName() {
- return `${this._module.getName()}.${this._name}`;
- }
-
- public getPriority() {
- return this._priority;
- }
-
- public getUuid() {
- return this._uuid;
- }
-
- public getStatus() {
- return this._status;
- }
-
- private _setStatus(status: JobStatus) {
- this._status = status;
- }
-
- public getModule() {
- return this._module;
- }
-
- public async execute() {
- if (this._startedAt) throw new Error("Job has already been executed.");
- if (!this.getModule().canRunJobs())
- throw new Error("Module can not currently run jobs.");
- this._setStatus(JobStatus.ACTIVE);
- this._startedAt = performance.now();
- return (
- this._jobFunction
- .apply(this._module, [this._context, this._payload])
-
-
- .then(response => {
- this.log({
- message: "Job completed successfully",
- type: "success"
- });
- JobStatistics.updateStats(this.getName(), "successful");
- return response;
- })
- .catch((err: any) => {
- this.log({
- message: `Job failed with error "${err}"`,
- type: "error",
- data: { error: err }
- });
- JobStatistics.updateStats(this.getName(), "failed");
- throw err;
- })
- .finally(() => {
- this._completedAt = performance.now();
- JobStatistics.updateStats(this.getName(), "total");
- if (this._startedAt)
- JobStatistics.updateStats(
- this.getName(),
- "duration",
- this._completedAt - this._startedAt
- );
- this._setStatus(JobStatus.COMPLETED);
- })
- );
- }
-
- public log(log: string | Omit<Log, "timestamp" | "category">) {
- const {
- message,
- type = undefined,
- data = {}
- } = {
- ...(typeof log === "string" ? { message: log } : log)
- };
- LogBook.log({
- message,
- type,
- category: this.getName(),
- data: {
- ...this.toJSON(),
- ...data
- }
- });
- }
-
- public toJSON() {
- return {
- uuid: this.getUuid(),
- priority: this.getPriority(),
- name: this.getName(),
- status: this.getStatus(),
- moduleStatus: this._module.getStatus(),
- createdAt: this._createdAt,
- startedAt: this._startedAt,
- completedAt: this._completedAt
- };
- }
- }
|