소스 검색

refactor: improved child job handling in new job/module system

Kristian Vos 2 년 전
부모
커밋
16e497be60
4개의 변경된 파일28개의 추가작업 그리고 2개의 파일을 삭제
  1. 24 1
      backend/src/Job.ts
  2. 2 0
      backend/src/JobQueue.ts
  3. 1 0
      backend/src/modules/StationModule.ts
  4. 1 1
      backend/src/types/JobStatus.ts

+ 24 - 1
backend/src/Job.ts

@@ -1,5 +1,6 @@
 import BaseModule from "./BaseModule";
 import JobQueue from "./JobQueue";
+import LogBook from "./LogBook";
 import { JobOptions } from "./types/JobOptions";
 import { JobStatus } from "./types/JobStatus";
 import { Jobs, Module, Modules } from "./types/Modules";
@@ -34,6 +35,8 @@ export default class Job {
 
 	protected jobQueue: JobQueue;
 
+	protected logBook: LogBook;
+
 	/**
 	 * Job
 	 *
@@ -54,6 +57,7 @@ export default class Job {
 		this.priority = 1;
 
 		this.jobQueue = new JobQueue();
+		this.logBook = LogBook.getPrimaryInstance();
 
 		if (options) {
 			const { priority, longJob } = options;
@@ -177,6 +181,25 @@ export default class Job {
 		payload: PayloadType,
 		options?: JobOptions
 	): Promise<ReturnType> {
-		return this.jobQueue.runJob(moduleName, jobName, payload, options);
+		if (this.getStatus() !== "ACTIVE")
+			throw new Error(
+				`Cannot run a child job when the current job is not active. Current job: ${this.getName()}, attempted to run job: ${moduleName}.${jobName.toString()}.`
+			);
+
+		return new Promise<Awaited<Promise<ReturnType>>>((resolve, reject) => {
+			this.jobQueue
+				.runJob(moduleName, jobName, payload, options)
+				// @ts-ignore
+				.then(resolve)
+				.catch(reject)
+				.finally(() => {
+					if (this.getStatus() !== "ACTIVE")
+						this.logBook.log({
+							type: "error",
+							category: "jobs",
+							message: `Job ${this.getName()}(${this.getUuid()}) has had a child job (${moduleName}.${jobName.toString()}) complete, but the job was not active. This should never happen!`
+						});
+				});
+		});
 	}
 }

+ 2 - 0
backend/src/JobQueue.ts

@@ -207,6 +207,8 @@ export default class JobQueue {
 					Date.now() - startTime
 				);
 
+				job.setStatus("COMPLETED");
+
 				// If the current job is in the active jobs array, remove it, and then run the process function to run another job
 				const activeJobIndex = this.active.indexOf(job);
 				if (activeJobIndex > -1) {

+ 1 - 0
backend/src/modules/StationModule.ts

@@ -43,6 +43,7 @@ export default class StationModule extends BaseModule {
 
 	public async addB(context: JobContext) {
 		context.log("ADDB");
+		await context.runJob("stations", "addToQueue", { songId: "test" });
 		await context.runJob("stations", "addC", {});
 	}
 

+ 1 - 1
backend/src/types/JobStatus.ts

@@ -1 +1 @@
-export type JobStatus = "QUEUED" | "ACTIVE" | "PAUSED";
+export type JobStatus = "QUEUED" | "ACTIVE" | "PAUSED" | "COMPLETED";