diff --git a/src/node/heart.ts b/src/node/heart.ts index b78f4edb80d2..911020d13261 100644 --- a/src/node/heart.ts +++ b/src/node/heart.ts @@ -43,6 +43,19 @@ export class Heart { return } + return this.pulse() + } + + /** + * Write to the heartbeat file and schedule the next activity check. + * + * The timer calls this instead of `beat` because timers and `Date.now()` use + * different clocks, so the timer can fire when `Date.now()` shows slightly + * less than a full interval since the last beat. `alive` would still be true + * then and `beat` would return without scheduling another check, which stops + * the heartbeat until the next HTTP request. + */ + private async pulse(): Promise { logger.debug("heartbeat") this.lastHeartbeat = Date.now() if (typeof this.heartbeatTimer !== "undefined") { @@ -52,7 +65,7 @@ export class Heart { this.heartbeatTimer = setTimeout(async () => { try { if (await this.isActive()) { - this.beat() + this.pulse() } else { this.setState("expired") } diff --git a/test/unit/node/heart.test.ts b/test/unit/node/heart.test.ts index 85b1945e3760..6999dd387b3e 100644 --- a/test/unit/node/heart.test.ts +++ b/test/unit/node/heart.test.ts @@ -115,6 +115,24 @@ describe("heartbeatTimer", () => { expect(mockIsActive).toHaveBeenCalled() }) + it("should keep beating when the timer fires before Date.now() shows a full interval", async () => { + const mockIsActive = jest.fn().mockResolvedValue(true) + const heart = new Heart(`${testDir}/shutdown.txt`, mockIsActive) + await heart.beat() + // Timers and Date.now() do not share a clock, so the timer can fire when + // Date.now() is still a little short of the full interval. + jest.setSystemTime(Date.now() - 1) + jest.advanceTimersByTime(60 * 1000) + expect(mockIsActive).toHaveBeenCalledTimes(1) + + // Let the timer callback finish so it can schedule the next check. + await new Promise((resolve) => setImmediate(resolve)) + + jest.advanceTimersByTime(60 * 1000) + expect(mockIsActive).toHaveBeenCalledTimes(2) + heart.dispose() + }) + it("should log a warning when isActive rejects", async () => { const error = new Error("oh no") const mockIsActive = jest.fn().mockRejectedValue(error)