| 2 | import { Job } from "./types" |
| 3 | |
| 4 | export class Worker<T> { |
| 5 | private queue: Queue<T> |
| 6 | private processJob: (job: Job<T>) => Promise<void> |
| 7 | private concurrency |
| 8 | private activeJobs: Map<string, Promise<void>> = new Map() |
| 9 | |
| 10 | constructor( |
| 11 | queue: Queue<T>, |
| 12 | processJob: (job: Job<T>) => Promise<void>, |
| 13 | { concurrency = 1 } = {} |
| 14 | ) { |
| 15 | this.processJob = processJob |
| 16 | this.queue = queue |
| 17 | this.concurrency = concurrency |
| 18 | } |
| 19 | |
| 20 | async start() { |
| 21 | while (true) { |
| 22 | const job = await this.queue.getOrWaitForJob() |
| 23 | if (job == null) { |
| 24 | await new Promise(resolve => setTimeout(resolve, 15000)) |
| 25 | } else { |
| 26 | this.activeJobs.set( |
| 27 | job.id, |
| 28 | this.processJob(job) |
| 29 | .catch(async () => { |
| 30 | await this.queue.addJob({ |
| 31 | ...job, |
| 32 | options: { |
| 33 | ...job.options, |
| 34 | retry: { |
| 35 | ...job.options.retry, |
| 36 | totalAttempts: job.options.retry.totalAttempts + 1, |
| 37 | }, |
| 38 | delay: |
| 39 | job.options.retry.delay * |
| 40 | (job.options.retry.totalAttempts + 1) ** 2, |
| 41 | }, |
| 42 | }) |
| 43 | }) |
| 44 | .finally(() => { |
| 45 | this.activeJobs.delete(job.id) |
| 46 | }) |
| 47 | ) |
| 48 | } |
| 49 | if (this.activeJobs.size >= this.concurrency) { |
| 50 | await Promise.any(this.activeJobs.values()) |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
nothing calls this directly
no outgoing calls
no test coverage detected