oneuptime/CommonServer/Infrastructure/Queue.ts

87 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-02-16 22:16:24 +00:00
import { Queue as BullQueue, JobsOptions, Job } from 'bullmq';
2023-02-15 14:54:13 +00:00
import { JSONObject } from 'Common/Types/JSON';
2023-09-11 10:29:36 +00:00
import { RedisHostname, RedisPassword, RedisPort } from '../EnvironmentConfig';
2023-02-15 14:54:13 +00:00
export enum QueueName {
2023-02-16 22:45:22 +00:00
Workflow = 'Workflow',
2023-03-02 19:36:06 +00:00
Worker = 'Worker',
2023-02-15 14:54:13 +00:00
}
2023-02-16 22:16:24 +00:00
export type QueueJob = Job;
2023-02-15 14:54:13 +00:00
export default class Queue {
public static getQueue(queueName: QueueName): BullQueue {
2023-02-16 22:16:24 +00:00
return new BullQueue(queueName, {
connection: {
host: RedisHostname.toString(),
2023-02-16 22:45:22 +00:00
port: RedisPort.toNumber(),
2023-02-18 21:39:52 +00:00
password: RedisPassword,
2023-02-16 22:45:22 +00:00
},
2023-02-16 22:16:24 +00:00
});
2023-02-15 14:54:13 +00:00
}
2023-02-28 23:18:01 +00:00
public static async removeJob(
queueName: QueueName,
2023-03-01 09:27:18 +00:00
jobId: string
2023-02-28 23:18:01 +00:00
): Promise<void> {
2023-03-01 22:20:15 +00:00
if (!jobId) {
2023-03-01 22:15:25 +00:00
return;
}
2023-03-01 09:27:18 +00:00
const job: Job | undefined = await this.getQueue(queueName).getJob(
jobId
);
2023-02-28 23:18:01 +00:00
if (job) {
await job.remove();
}
// remove existing repeatable job
2023-03-01 09:27:18 +00:00
await this.getQueue(queueName).removeRepeatableByKey(jobId);
2023-02-28 23:18:01 +00:00
}
2023-02-16 22:45:22 +00:00
public static async addJob(
queueName: QueueName,
2023-02-28 22:21:33 +00:00
jobId: string,
2023-02-16 22:45:22 +00:00
jobName: string,
data: JSONObject,
options?: {
2023-02-28 22:21:33 +00:00
scheduleAt?: string | undefined;
repeatableKey?: string | undefined;
2023-02-16 22:45:22 +00:00
}
2023-02-28 22:21:33 +00:00
): Promise<Job> {
2023-02-16 22:16:24 +00:00
const optionsObject: JobsOptions = {
2023-02-16 22:45:22 +00:00
jobId: jobId.toString(),
2023-02-16 22:16:24 +00:00
};
2023-02-16 22:45:22 +00:00
if (options && options.scheduleAt) {
2023-02-16 22:16:24 +00:00
optionsObject.repeat = {
2023-02-16 22:45:22 +00:00
pattern: options.scheduleAt,
};
2023-02-16 22:16:24 +00:00
}
2023-03-01 09:27:18 +00:00
const job: Job | undefined = await this.getQueue(queueName).getJob(
jobId
);
2023-02-28 22:21:33 +00:00
2023-02-28 23:18:01 +00:00
if (job) {
2023-02-28 22:21:33 +00:00
await job.remove();
}
2023-02-28 23:18:01 +00:00
if (options?.repeatableKey) {
2023-02-28 22:21:33 +00:00
// remove existing repeatable job
2023-03-01 09:27:18 +00:00
await this.getQueue(queueName).removeRepeatableByKey(
options?.repeatableKey
);
2023-02-28 22:21:33 +00:00
}
2023-03-01 09:27:18 +00:00
const jobAdded: Job = await this.getQueue(queueName).add(
jobName,
data,
optionsObject
);
2023-02-28 22:21:33 +00:00
return jobAdded;
2023-02-15 14:54:13 +00:00
}
2023-02-16 22:45:22 +00:00
}