* Starts the job as soon as there is capacity. Jobs with the same key never overlap. * * @param key Identifies the resource the job touches * @param bytes The amount of memory the job keeps * @param job The work * @throws {unknown} The failure of any previously submitted job
(key: string, bytes: number, job: () => Promise<void>)
| 38 | * @throws {unknown} The failure of any previously submitted job |
| 39 | */ |
| 40 | async submit(key: string, bytes: number, job: () => Promise<void>): Promise<void> { |
| 41 | this.throwIfFailed(); |
| 42 | await this.waitForKey(key); |
| 43 | while (this.running.size >= this.maxJobs || (this.running.size > 0 && this.runningBytes + bytes > this.maxBytes)) { |
| 44 | await Promise.race(this.running); |
| 45 | this.throwIfFailed(); |
| 46 | } |
| 47 | |
| 48 | this.runningKeys.add(key); |
| 49 | this.runningBytes += bytes; |
| 50 | // oxlint-disable-next-line promise/prefer-await-to-then -- the task must remove itself from the set |
| 51 | const task: Promise<boolean> = this.execute(key, bytes, job).then(() => this.running.delete(task)); |
| 52 | this.running.add(task); |
| 53 | } |
| 54 | |
| 55 | /** Waits until no job with this key is running. */ |
| 56 | async waitForKey(key: string): Promise<void> { |
no test coverage detected