/** * @file Tests server/lib/backoff-poll.js — the poll that runs at its base pace * while passes find work (or fail) and slows to its idle pace after a pass * that resolved `false`, returning to the base pace once work shows up again. * @author Nguyễn Ngọc Trí Vĩ */ const { describe, it } = require("node:test"); const assert = require("node:assert/strict"); const { startBackoffPoll, idleDefault } = require("../lib/backoff-poll"); const wait = (ms) => new Promise((r) => setTimeout(r, ms)); describe("startBackoffPoll", () => { it("slows down after idle passes and speeds up again on work", async () => { const answers = [true, false, false, true, "x"]; const at = []; const t0 = Date.now(); const poll = startBackoffPoll( () => { at.push(Date.now() - t0); const a = answers.shift(); if (a === "x") throw new Error("boom"); return a; }, { baseMs: 10, idleMs: 80 } ); await wait(260); poll.stop(); assert.ok(at.length >= 5, `ran ${at.length} times`); const gaps = at.slice(1).map((t, i) => t - at[i]); assert.ok(gaps[0] < 60, "work → base pace"); assert.ok(gaps[1] >= 75, "idle → idle pace"); assert.ok(gaps[2] >= 75, "still idle"); assert.ok(gaps[3] < 60, "work again → base pace"); }); it("idles at a minute by default, never faster than the base pace", () => { assert.equal(idleDefault(15_000), 60_000); assert.equal(idleDefault(120_000), 120_000); }); });