Skip to content
Myr

concurrent.test.ts

This file

Path

src/utils/concurrent.test.ts

69 lines · 2.1 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–69why, one step back
1import { createPool } from './concurrent'
23describe('concurrent execution', () => {4 test.each`5 concurrency | count6 ${1} | ${10}7 ${10} | ${10}8 ${100} | ${10}9 ${Infinity} | ${2000}10 `('concurrency $concurrency, count $count', async ({ concurrency, count }) => {11 const running = new Set()1213 const pool = createPool({ concurrency })14 let resolve: (() => void) | undefined15 const promise = new Promise<void>((r) => {16 resolve = r17 })18 const fn = async (i: number) => {19 if (running.size > concurrency) {20 throw new Error('concurrency exceeded')21 }2223 running.add(i)24 await promise25 running.delete(i)26 return i27 }2829 const jobs = new Array(count).fill(0).map((_, i) => () => fn(i))30 const expectedResults = new Array(count).fill(0).map((_, i) => i)31 const resultPromises = jobs.map((job) => pool.run(job))3233 expect(running.size).toBe(Math.min(concurrency, count))34 resolve?.()35 const results = await Promise.all(resultPromises)36 expect(running.size).toBe(0)37 expect(results).toEqual(expectedResults)38 })3940 describe('with interval', () => {41 test.each`42 concurrency | interval43 ${1} | ${10}44 ${2} | ${10}45 `('concurrency $concurrency, interval $interval', async ({ concurrency, interval }) => {46 const workingTimeQueue: number[] = []47 const pool = createPool({ concurrency, interval })48 const fn = async (i: number) => {49 const now = Date.now()50 if (workingTimeQueue.length >= concurrency) {51 const last = workingTimeQueue.shift()52 // Not so accurate, -1 ms is acceptable53 if (last && now - last < interval - 1) {54 throw new Error('interval violated')55 }56 }57 workingTimeQueue.push(now)58 return i59 }6061 const jobs = new Array(10).fill(0).map((_, i) => () => fn(i))62 const expectedResults = new Array(10).fill(0).map((_, i) => i)63 const resultPromises = jobs.map((job) => pool.run(job))6465 const results = await Promise.all(resultPromises)66 expect(results).toEqual(expectedResults)67 })68 })69})