2022-05-18 08:19:32 +00:00
|
|
|
import pkg/chronos
|
2023-03-08 15:04:54 +00:00
|
|
|
import pkg/stew/endians2
|
|
|
|
import pkg/upraises
|
2022-05-18 08:19:32 +00:00
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
type
|
|
|
|
Clock* = ref object of RootObj
|
|
|
|
SecondsSince1970* = int64
|
2022-06-14 13:25:48 +00:00
|
|
|
Timeout* = object of CatchableError
|
2022-05-17 09:50:52 +00:00
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
method now*(clock: Clock): SecondsSince1970 {.base, upraises: [].} =
|
2022-05-17 09:50:52 +00:00
|
|
|
raiseAssert "not implemented"
|
2022-05-18 08:19:32 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
method waitUntil*(clock: Clock, time: SecondsSince1970) {.base,async.} =
|
2022-05-18 08:19:32 +00:00
|
|
|
while clock.now() < time:
|
|
|
|
await sleepAsync(1.seconds)
|
2022-06-14 13:25:48 +00:00
|
|
|
|
|
|
|
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")
|
2023-03-08 15:04:54 +00:00
|
|
|
|
|
|
|
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)
|