fix(companion): normalize heartbeat jitter random samples
This commit is contained in:
@@ -81,6 +81,32 @@ describe('CompanionHeartbeatLoop', () => {
|
||||
loop.stop();
|
||||
});
|
||||
|
||||
it('normalizes invalid randomFn samples for jitter scheduling', async () => {
|
||||
const publishHeartbeatHigh = vi.fn(async () => buildStatusResult());
|
||||
const loopHigh = new CompanionHeartbeatLoop(
|
||||
{ publishHeartbeat: publishHeartbeatHigh },
|
||||
{ intervalMs: 1000, jitterRatio: 0.5, randomFn: () => 2 },
|
||||
);
|
||||
loopHigh.start(false);
|
||||
await vi.advanceTimersByTimeAsync(1499);
|
||||
expect(publishHeartbeatHigh).toHaveBeenCalledTimes(0);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(publishHeartbeatHigh).toHaveBeenCalledTimes(1);
|
||||
loopHigh.stop();
|
||||
|
||||
const publishHeartbeatNaN = vi.fn(async () => buildStatusResult());
|
||||
const loopNaN = new CompanionHeartbeatLoop(
|
||||
{ publishHeartbeat: publishHeartbeatNaN },
|
||||
{ intervalMs: 1000, jitterRatio: 0.5, randomFn: () => Number.NaN },
|
||||
);
|
||||
loopNaN.start(false);
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(publishHeartbeatNaN).toHaveBeenCalledTimes(0);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(publishHeartbeatNaN).toHaveBeenCalledTimes(1);
|
||||
loopNaN.stop();
|
||||
});
|
||||
|
||||
it('calls onSuccess with heartbeat result payload', async () => {
|
||||
const result = buildStatusResult();
|
||||
const publishHeartbeat = vi.fn(async () => result);
|
||||
|
||||
@@ -154,7 +154,8 @@ export class CompanionHeartbeatLoop {
|
||||
}
|
||||
const minFactor = 1 - this.jitterRatio;
|
||||
const maxFactor = 1 + this.jitterRatio;
|
||||
const random = this.randomFn();
|
||||
const sampled = this.randomFn();
|
||||
const random = Number.isFinite(sampled) ? Math.max(0, Math.min(1, sampled)) : 0.5;
|
||||
const factor = minFactor + (maxFactor - minFactor) * random;
|
||||
return Math.max(1, Math.round(this.intervalMs * factor));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user