import { describe, expect, it } from 'vitest'; import { UploadSlots } from './upload-slots.js'; const slots = (max: number, perUser: number) => new UploadSlots({ getOrThrow: (key: string) => key === 'UPLOAD_MAX_IN_FLIGHT' ? max : perUser, } as never); function hold() { const { promise, resolve } = Promise.withResolvers(); return { work: () => promise, release: resolve }; } describe('UploadSlots', () => { it('caps one user without starving others, and frees slots after work', async () => { const limiter = slots(10, 2); const held = [hold(), hold()]; const running = held.map((h) => limiter.run('a', h.work)); await expect(limiter.run('a', async () => 'x')).rejects.toMatchObject({ status: 429, }); await expect(limiter.run('b', async () => 'ok')).resolves.toBe('ok'); held.forEach((h) => h.release()); await Promise.all(running); await expect(limiter.run('a', async () => 'again')).resolves.toBe( 'again', ); }); it('applies the replica-wide cap across users', async () => { const limiter = slots(2, 2); const held = [hold(), hold()]; const running = [ limiter.run('a', held[0].work), limiter.run('b', held[1].work), ]; await expect(limiter.run('c', async () => 'x')).rejects.toMatchObject({ status: 429, }); held.forEach((h) => h.release()); await Promise.all(running); }); it('releases a slot when the work fails', async () => { const limiter = slots(1, 1); await expect( limiter.run('a', async () => { throw new Error('boom'); }), ).rejects.toThrow('boom'); await expect(limiter.run('a', async () => 'ok')).resolves.toBe('ok'); }); });