2023-04-19 12:27:16 +00:00
|
|
|
|
## An extension wrapper around nim-chronos
|
2023-04-12 11:05:34 +00:00
|
|
|
|
when (NimMajor, NimMinor) < (1, 4):
|
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
else:
|
|
|
|
|
{.push raises: [].}
|
|
|
|
|
|
2023-04-19 12:27:16 +00:00
|
|
|
|
import
|
|
|
|
|
chronos,
|
|
|
|
|
chronicles
|
|
|
|
|
|
|
|
|
|
export chronos
|
2023-04-12 11:05:34 +00:00
|
|
|
|
|
|
|
|
|
|
2023-04-19 12:27:16 +00:00
|
|
|
|
## Extension methods
|
|
|
|
|
|
|
|
|
|
# Taken from: https://github.com/status-im/nim-libp2p/blob/master/libp2p/utils/heartbeat.nim
|
2023-04-12 11:05:34 +00:00
|
|
|
|
template heartbeat*(name: string, interval: Duration, body: untyped): untyped =
|
|
|
|
|
var nextHeartbeat = Moment.now()
|
|
|
|
|
while true:
|
|
|
|
|
body
|
|
|
|
|
|
|
|
|
|
nextHeartbeat += interval
|
|
|
|
|
let now = Moment.now()
|
|
|
|
|
if nextHeartbeat < now:
|
|
|
|
|
let
|
|
|
|
|
delay = now - nextHeartbeat
|
|
|
|
|
itv = interval
|
2023-04-19 12:27:16 +00:00
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
if delay > itv:
|
2023-04-19 12:27:16 +00:00
|
|
|
|
info "Missed multiple heartbeats", heartbeat = name, delay = delay, hinterval = itv
|
2023-04-12 11:05:34 +00:00
|
|
|
|
else:
|
2023-04-19 12:27:16 +00:00
|
|
|
|
debug "Missed heartbeat", heartbeat = name, delay = delay, hinterval = itv
|
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
nextHeartbeat = now + itv
|
2023-04-19 12:27:16 +00:00
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
await sleepAsync(nextHeartbeat - now)
|