nim-dagger/codex/clock.nim
markspanbroek 3879ec8e3a
[clock] waitUntil() completes immediately when block arrives (#475)
Previously it could take up to one second to complete
the future. This messed with the timings in the
integration tests and made them less predictable.
2023-07-13 11:19:45 +02:00

35 lines
957 B
Nim

import pkg/chronos
import pkg/stew/endians2
import pkg/upraises
type
Clock* = ref object of RootObj
SecondsSince1970* = int64
Timeout* = object of CatchableError
method now*(clock: Clock): SecondsSince1970 {.base, upraises: [].} =
raiseAssert "not implemented"
method waitUntil*(clock: Clock, time: SecondsSince1970) {.base, async.} =
raiseAssert "not implemented"
proc withTimeout*(future: Future[void],
clock: Clock,
expiry: SecondsSince1970) {.async.} =
let timeout = clock.waitUntil(expiry)
try:
await future or timeout
finally:
await timeout.cancelAndWait()
if not future.completed:
await future.cancelAndWait()
raise newException(Timeout, "Timed out")
proc toBytes*(i: SecondsSince1970): seq[byte] =
let asUint = cast[uint64](i)
@(asUint.toBytes)
proc toSecondsSince1970*(bytes: seq[byte]): SecondsSince1970 =
let asUint = uint64.fromBytes(bytes)
cast[int64](asUint)