Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/node/heart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
logger.debug("heartbeat")
this.lastHeartbeat = Date.now()
if (typeof this.heartbeatTimer !== "undefined") {
Expand All @@ -52,7 +65,7 @@ export class Heart {
this.heartbeatTimer = setTimeout(async () => {
try {
if (await this.isActive()) {
this.beat()
this.pulse()
} else {
this.setState("expired")
}
Expand Down
18 changes: 18 additions & 0 deletions test/unit/node/heart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading