import { Job, RawJob } from './models/Job'; export const CANCEL = 'rn_job_queue_cancel'; export interface WorkerOptions
{ onStart?: (job: Job
) => void; onSuccess?: (job: Job
) => void; onFailure?: (job: Job
, error: Error) => void; onCompletion?: (job: Job
) => void;
concurrency?: number;
}
export interface CancellablePromise {
public readonly name: string;
public readonly concurrency: number;
private executionCount: number;
private executer: (payload: P, id: string) => CancellablePromise ) => void;
private onSuccess: (job: Job ) => void;
private onFailure: (job: Job , error: Error) => void;
private onCompletion: (job: Job ) => void;
/**
*
* @typeparam P specifies the type of the job-payload.
* @param name of worker
* @param executer function to run jobs
* @param options to configure worker
*/
constructor(name: string, executer: (payload: P, id: string) => Promise = {}) {
const {
onStart = (job: Job ) => {},
onSuccess = (job: Job ) => {},
onFailure = (job: Job , error: Error) => {},
onCompletion = (job: Job ) => {},
concurrency = 5,
} = options;
this.name = name;
this.concurrency = concurrency;
this.executionCount = 0;
this.executer = executer;
this.onStart = onStart;
this.onSuccess = onSuccess;
this.onFailure = onFailure;
this.onCompletion = onCompletion;
}
/**
* @returns true if worker runs max concurrent amout of jobs
*/
get isBusy() {
return this.executionCount === this.concurrency;
}
/**
* @returns amount of available Executers for current worker
*/
get availableExecuters() {
return this.concurrency - this.executionCount;
}
/**
* This method should not be invoked manually and is used by the queue to execute jobs
* @param job to be executed
*/
execute(rawJob: RawJob) {
const { timeout } = rawJob;
const payload: P = JSON.parse(rawJob.payload);
const job = { ...rawJob, ...{ payload } };
this.executionCount++;
this.onStart(job);
if (timeout > 0) {
return this.executeWithTimeout(job, timeout);
} else {
return this.executer(payload, job.id);
}
}
private executeWithTimeout(job: Job , timeout: number) {
let cancel;
const promise: CancellablePromise ) {
this.onSuccess(job);
}
triggerFailure(job: Job , error: Error) {
this.onFailure(job, error);
}
triggerCompletion(job: Job ) {
this.onCompletion(job);
}
decreaseExecutionCount() {
this.executionCount--;
}
}