| 1 | import { describe, expect, it } from "vitest"; |
| 2 | import { MemoryPool } from "../../src/lib/memory-pool.js"; |
| 3 | |
| 4 | const tick = () => new Promise((r) => setTimeout(r, 0)); |
| 5 | |
| 6 | describe("MemoryPool", () => { |
| 7 | it("gives shares that fit at once, and makes the rest wait, oldest first", async () => { |
| 8 | const pool = new MemoryPool(100); |
| 9 | const a = await pool.take(60); |
| 10 | const b = await pool.take(30); |
| 11 | expect(pool.fits(10)).toBe(true); |
| 12 | const order: string[] = []; |
| 13 | const c = pool.take(50).then((l) => (order.push("c"), l)); |
| 14 | // A small one that would fit still waits behind the large one, so the large one isn't starved. |
| 15 | expect(pool.fits(10)).toBe(false); |
| 16 | const d = pool.take(10).then((l) => (order.push("d"), l)); |
| 17 | await tick(); |
| 18 | expect(order).toEqual([]); |
| 19 | a.release(); |
| 20 | a.release(); // a second release gives nothing back twice |
| 21 | await tick(); |
| 22 | expect(order).toEqual(["c", "d"]); |
| 23 | (await c).release(); |
| 24 | (await d).release(); |
| 25 | b.release(); |
| 26 | expect(pool.fits(100)).toBe(true); |
| 27 | }); |
| 28 | |
| 29 | it("a share larger than the pool gets all of it, alone", async () => { |
| 30 | const pool = new MemoryPool(100); |
| 31 | const small = await pool.take(1); |
| 32 | let got = false; |
| 33 | const big = pool.take(500).then((l) => ((got = true), l)); |
| 34 | await tick(); |
| 35 | expect(got).toBe(false); |
| 36 | small.release(); |
| 37 | const lease = await big; |
| 38 | expect(lease.bytes).toBe(100); |
| 39 | expect(pool.fits(1)).toBe(false); |
| 40 | lease.release(); |
| 41 | expect(pool.fits(100)).toBe(true); |
| 42 | }); |
| 43 | |
| 44 | it("grows a share by giving it back and waiting its turn for the larger one", async () => { |
| 45 | const pool = new MemoryPool(100); |
| 46 | const a = await pool.take(10); |
| 47 | const b = await pool.take(50); |
| 48 | let grown = false; |
| 49 | const growing = a.grow(80).then(() => (grown = true)); |
| 50 | await tick(); |
| 51 | expect(grown).toBe(false); |
| 52 | b.release(); |
| 53 | await growing; |
| 54 | expect(a.bytes).toBe(80); |
| 55 | await a.grow(20); // already large enough |
| 56 | expect(a.bytes).toBe(80); |
| 57 | a.release(); |
| 58 | expect(pool.fits(100)).toBe(true); |
| 59 | }); |
| 60 | }); |