Rework retry_wrapper from template to proc

This commit is contained in:
stubbsta 2025-12-19 09:00:29 +02:00
parent 9b6b33f0e5
commit 879c79161f
No known key found for this signature in database
2 changed files with 95 additions and 62 deletions

View File

@ -148,12 +148,6 @@ template initializedGuard(g: OnchainGroupManager): untyped =
if not g.initialized: if not g.initialized:
raise newException(CatchableError, "OnchainGroupManager is not initialized") raise newException(CatchableError, "OnchainGroupManager is not initialized")
template retryWrapper(
g: OnchainGroupManager, res: auto, errStr: string, body: untyped
): auto =
retryWrapper(res, RetryStrategy.new(), errStr, g.onFatalErrorAction):
body
proc updateRoots*(g: OnchainGroupManager): Future[bool] {.async.} = proc updateRoots*(g: OnchainGroupManager): Future[bool] {.async.} =
let rootRes = (await g.fetchMerkleRoot()).valueOr: let rootRes = (await g.fetchMerkleRoot()).valueOr:
return false return false
@ -172,7 +166,7 @@ proc updateRoots*(g: OnchainGroupManager): Future[bool] {.async.} =
return false return false
proc trackRootChanges*(g: OnchainGroupManager) {.async: (raises: [CatchableError]).} = proc trackRootChanges*(g: OnchainGroupManager): Future[Result[void, string]] {.async.} =
try: try:
initializedGuard(g) initializedGuard(g)
const rpcDelay = 5.seconds const rpcDelay = 5.seconds
@ -194,18 +188,21 @@ proc trackRootChanges*(g: OnchainGroupManager) {.async: (raises: [CatchableError
let nextFreeIndex = (await g.fetchNextFreeIndex()).valueOr: let nextFreeIndex = (await g.fetchNextFreeIndex()).valueOr:
error "Failed to fetch next free index", error = error error "Failed to fetch next free index", error = error
raise return err("Failed to fetch next free index: " & error)
newException(CatchableError, "Failed to fetch next free index: " & error)
let memberCount = cast[int64](nextFreeIndex) let memberCount = cast[int64](nextFreeIndex)
waku_rln_number_registered_memberships.set(float64(memberCount)) waku_rln_number_registered_memberships.set(float64(memberCount))
except CatchableError: except CatchableError:
error "Fatal error in trackRootChanges", error = getCurrentExceptionMsg() error "Fatal error in trackRootChanges", error = getCurrentExceptionMsg()
return err("Fatal error in trackRootChanges" & getCurrentExceptionMsg())
method register*( method register*(
g: OnchainGroupManager, rateCommitment: RateCommitment g: OnchainGroupManager, rateCommitment: RateCommitment
): Future[void] {.async: (raises: [Exception]).} = ): Future[Result[void, string]] {.async.} =
initializedGuard(g) try:
initializedGuard(g)
except CatchableError as e:
return err("Not initialized: " & e.msg)
try: try:
let leaf = rateCommitment.toLeaf().get() let leaf = rateCommitment.toLeaf().get()
@ -214,33 +211,41 @@ method register*(
info "registering member via callback", rateCommitment = leaf, index = idx info "registering member via callback", rateCommitment = leaf, index = idx
await g.registerCb.get()(@[Membership(rateCommitment: leaf, index: idx)]) await g.registerCb.get()(@[Membership(rateCommitment: leaf, index: idx)])
g.latestIndex.inc() g.latestIndex.inc()
except CatchableError: except Exception as e:
raise newException(ValueError, getCurrentExceptionMsg()) return err("Failed to call register callback: " & e.msg)
method register*( method register*(
g: OnchainGroupManager, g: OnchainGroupManager,
identityCredential: IdentityCredential, identityCredential: IdentityCredential,
userMessageLimit: UserMessageLimit, userMessageLimit: UserMessageLimit,
): Future[void] {.async: (raises: [Exception]).} = ): Future[Result[void, string]] {.async.} =
initializedGuard(g) try:
initializedGuard(g)
except CatchableError as e:
return err("Not initialized: " & e.msg)
let ethRpc = g.ethRpc.get() let ethRpc = g.ethRpc.get()
let wakuRlnContract = g.wakuRlnContract.get() let wakuRlnContract = g.wakuRlnContract.get()
var gasPrice: int let gasPrice = (
g.retryWrapper(gasPrice, "Failed to get gas price"): await retryWrapper(
let fetchedGasPrice = uint64(await ethRpc.provider.eth_gasPrice()) RetryStrategy.new(),
## Multiply by 2 to speed up the transaction "Failed to get gas price",
## Check for overflow when casting to int proc(): Future[int] {.async.} =
if fetchedGasPrice > uint64(high(int) div 2): let fetchedGasPrice = uint64(await ethRpc.provider.eth_gasPrice())
warn "Gas price overflow detected, capping at maximum int value", if fetchedGasPrice > uint64(high(int) div 2):
fetchedGasPrice = fetchedGasPrice, maxInt = high(int) warn "Gas price overflow detected, capping at maximum int value",
high(int) fetchedGasPrice = fetchedGasPrice, maxInt = high(int)
else: return high(int)
let calculatedGasPrice = int(fetchedGasPrice) * 2 else:
debug "Gas price calculated", let calculatedGasPrice = int(fetchedGasPrice) * 2
fetchedGasPrice = fetchedGasPrice, gasPrice = calculatedGasPrice debug "Gas price calculated",
calculatedGasPrice fetchedGasPrice = fetchedGasPrice, gasPrice = calculatedGasPrice
return calculatedGasPrice,
)
).valueOr:
return err("Failed to get gas price: " & error)
let idCommitmentHex = identityCredential.idCommitment.inHex() let idCommitmentHex = identityCredential.idCommitment.inHex()
debug "identityCredential idCommitmentHex", idCommitment = idCommitmentHex debug "identityCredential idCommitmentHex", idCommitment = idCommitmentHex
let idCommitment = identityCredential.idCommitment.toUInt256() let idCommitment = identityCredential.idCommitment.toUInt256()
@ -249,16 +254,28 @@ method register*(
idCommitment = idCommitment, idCommitment = idCommitment,
userMessageLimit = userMessageLimit, userMessageLimit = userMessageLimit,
idCommitmentsToErase = idCommitmentsToErase idCommitmentsToErase = idCommitmentsToErase
var txHash: TxHash let txHash = (
g.retryWrapper(txHash, "Failed to register the member"): await retryWrapper(
await wakuRlnContract RetryStrategy.new(),
.register(idCommitment, userMessageLimit.stuint(32), idCommitmentsToErase) "Failed to register the member",
.send(gasPrice = gasPrice) proc(): Future[TxHash] {.async.} =
return await wakuRlnContract
.register(idCommitment, userMessageLimit.stuint(32), idCommitmentsToErase)
.send(gasPrice = gasPrice),
)
).valueOr:
return err("Failed to register member: " & error)
# wait for the transaction to be mined # wait for the transaction to be mined
var tsReceipt: ReceiptObject let tsReceipt = (
g.retryWrapper(tsReceipt, "Failed to get the transaction receipt"): await retryWrapper(
await ethRpc.getMinedTransactionReceipt(txHash) RetryStrategy.new(),
"Failed to get the transaction receipt",
proc(): Future[ReceiptObject] {.async.} =
return await ethRpc.getMinedTransactionReceipt(txHash),
)
).valueOr:
return err("Failed to get transaction receipt: " & error)
debug "registration transaction mined", txHash = txHash debug "registration transaction mined", txHash = txHash
g.registrationTxHash = some(txHash) g.registrationTxHash = some(txHash)
# the receipt topic holds the hash of signature of the raised events # the receipt topic holds the hash of signature of the raised events
@ -309,10 +326,13 @@ method register*(
if g.registerCb.isSome(): if g.registerCb.isSome():
let member = Membership(rateCommitment: rateCommitment, index: g.latestIndex) let member = Membership(rateCommitment: rateCommitment, index: g.latestIndex)
await g.registerCb.get()(@[member]) try:
await g.registerCb.get()(@[member])
except Exception as e:
return err("Failed to call register callback: " & e.msg)
g.latestIndex.inc() g.latestIndex.inc()
return return ok()
method withdraw*( method withdraw*(
g: OnchainGroupManager, idCommitment: IDCommitment g: OnchainGroupManager, idCommitment: IDCommitment
@ -492,25 +512,30 @@ method onWithdraw*(g: OnchainGroupManager, cb: OnWithdrawCallback) {.gcsafe.} =
proc establishConnection( proc establishConnection(
g: OnchainGroupManager g: OnchainGroupManager
): Future[GroupManagerResult[Web3]] {.async.} = ): Future[GroupManagerResult[Web3]] {.async.} =
var ethRpc: Web3 let ethRpc = (
await retryWrapper(
RetryStrategy.new(),
"Failed to connect to the Ethereum client",
proc(): Future[Web3] {.async.} =
var innerEthRpc: Web3
var connected = false
for clientUrl in g.ethClientUrls:
## We give a chance to the user to provide multiple clients
## and we try to connect to each of them
try:
innerEthRpc = await newWeb3(clientUrl)
connected = true
break
except CatchableError:
error "failed connect Eth client", error = getCurrentExceptionMsg()
g.retryWrapper(ethRpc, "Failed to connect to the Ethereum client"): if not connected:
var innerEthRpc: Web3 raise newException(CatchableError, "all failed")
var connected = false
for clientUrl in g.ethClientUrls:
## We give a chance to the user to provide multiple clients
## and we try to connect to each of them
try:
innerEthRpc = await newWeb3(clientUrl)
connected = true
break
except CatchableError:
error "failed connect Eth client", error = getCurrentExceptionMsg()
if not connected: return innerEthRpc,
raise newException(CatchableError, "all failed") )
).valueOr:
innerEthRpc return err("Failed to establish Ethereum connection: " & error)
return ok(ethRpc) return ok(ethRpc)
@ -519,9 +544,15 @@ method init*(g: OnchainGroupManager): Future[GroupManagerResult[void]] {.async.}
let ethRpc: Web3 = (await establishConnection(g)).valueOr: let ethRpc: Web3 = (await establishConnection(g)).valueOr:
return err("failed to connect to Ethereum clients: " & $error) return err("failed to connect to Ethereum clients: " & $error)
var fetchedChainId: UInt256 let fetchedChainId = (
g.retryWrapper(fetchedChainId, "Failed to get the chain id"): await retryWrapper(
await ethRpc.provider.eth_chainId() RetryStrategy.new(),
"Failed to get the chain id",
proc(): Future[UInt256] {.async.} =
return await ethRpc.provider.eth_chainId(),
)
).valueOr:
return err("Failed to get chain id: " & error)
# Set the chain id # Set the chain id
if g.chainId == 0: if g.chainId == 0:
@ -595,8 +626,10 @@ method init*(g: OnchainGroupManager): Future[GroupManagerResult[void]] {.async.}
proc onDisconnect() {.async.} = proc onDisconnect() {.async.} =
error "Ethereum client disconnected" error "Ethereum client disconnected"
var newEthRpc: Web3 = (await g.establishConnection()).valueOr: let newEthRpc: Web3 = (await g.establishConnection()).valueOr:
g.onFatalErrorAction("failed to connect to Ethereum clients onDisconnect") error "Fatal: failed to reconnect to Ethereum clients after disconnect",
error = error
g.onFatalErrorAction("failed to reconnect to Ethereum clients: " & error)
return return
newEthRpc.ondisconnect = ethRpc.ondisconnect newEthRpc.ondisconnect = ethRpc.ondisconnect

View File

@ -64,7 +64,7 @@ type WakuRLNRelay* = ref object of RootObj
onFatalErrorAction*: OnFatalErrorHandler onFatalErrorAction*: OnFatalErrorHandler
nonceManager*: NonceManager nonceManager*: NonceManager
epochMonitorFuture*: Future[void] epochMonitorFuture*: Future[void]
rootChangesFuture*: Future[void] rootChangesFuture*: Future[Result[void, string]]
proc calcEpoch*(rlnPeer: WakuRLNRelay, t: float64): Epoch = proc calcEpoch*(rlnPeer: WakuRLNRelay, t: float64): Epoch =
## gets time `t` as `flaot64` with subseconds resolution in the fractional part ## gets time `t` as `flaot64` with subseconds resolution in the fractional part