Rework retry_wrapper from template to proc

This commit is contained in:
stubbsta 2025-12-19 08:59:48 +02:00
parent 834eea945d
commit 9b6b33f0e5
No known key found for this signature in database

View File

@ -1,36 +1,33 @@
import ../../../common/error_handling
import chronos import chronos
import results import results
const
DefaultRetryDelay* = 4000.millis
DefaultRetryCount* = 15'u
type RetryStrategy* = object type RetryStrategy* = object
shouldRetry*: bool
retryDelay*: Duration retryDelay*: Duration
retryCount*: uint retryCount*: uint
proc new*(T: type RetryStrategy): RetryStrategy = proc new*(T: type RetryStrategy): RetryStrategy =
return RetryStrategy(shouldRetry: true, retryDelay: 4000.millis, retryCount: 15) return RetryStrategy(retryDelay: DefaultRetryDelay, retryCount: DefaultRetryCount)
template retryWrapper*( proc retryWrapper*[T](
res: auto,
retryStrategy: RetryStrategy, retryStrategy: RetryStrategy,
errStr: string, errStr: string,
errCallback: OnFatalErrorHandler, body: proc(): Future[T] {.async.},
body: untyped, ): Future[Result[T, string]] {.async.} =
): auto =
if errCallback == nil:
raise newException(CatchableError, "Ensure that the errCallback is set")
var retryCount = retryStrategy.retryCount var retryCount = retryStrategy.retryCount
var shouldRetry = retryStrategy.shouldRetry var lastError = ""
var exceptionMessage = ""
while shouldRetry and retryCount > 0: while retryCount > 0:
try: try:
res = body let value = await body()
shouldRetry = false return ok(value)
except: except CatchableError as e:
retryCount -= 1 retryCount -= 1
exceptionMessage = getCurrentExceptionMsg() lastError = e.msg
await sleepAsync(retryStrategy.retryDelay) if retryCount > 0:
if shouldRetry: await sleepAsync(retryStrategy.retryDelay)
errCallback(errStr & ": " & exceptionMessage)
return return err(errStr & ": " & lastError)