From 3f627790f8644580d5ab4f1cfb446622ebc90352 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Tue, 17 May 2022 16:40:21 +0200 Subject: [PATCH] [proving] Ensure that proving is completely stopped --- dagger/contracts/interactions.nim | 4 ++-- dagger/proving.nim | 18 ++++++++++++------ tests/dagger/testproving.nim | 4 ++-- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/dagger/contracts/interactions.nim b/dagger/contracts/interactions.nim index 26e32b6e..347ce33e 100644 --- a/dagger/contracts/interactions.nim +++ b/dagger/contracts/interactions.nim @@ -66,8 +66,8 @@ proc new*(_: type ContractInteractions): ?ContractInteractions = proc start*(interactions: ContractInteractions) {.async.} = interactions.sales.start() - interactions.proving.start() + await interactions.proving.start() proc stop*(interactions: ContractInteractions) {.async.} = interactions.sales.stop() - interactions.proving.stop() + await interactions.proving.stop() diff --git a/dagger/proving.nim b/dagger/proving.nim index 90347d57..f711decf 100644 --- a/dagger/proving.nim +++ b/dagger/proving.nim @@ -11,7 +11,7 @@ export proofs type Proving* = ref object proofs: Proofs - stopped: bool + loop: ?Future[void] contracts*: HashSet[ContractId] onProofRequired: ?OnProofRequired OnProofRequired* = proc (id: ContractId) {.gcsafe, upraises:[].} @@ -35,7 +35,7 @@ proc removeEndedContracts(proving: Proving) {.async.} = proc run(proving: Proving) {.async.} = try: - while not proving.stopped: + while true: let currentPeriod = await proving.proofs.getCurrentPeriod() await proving.removeEndedContracts() for id in proving.contracts: @@ -47,11 +47,17 @@ proc run(proving: Proving) {.async.} = except CatchableError as e: error "Proving failed", msg = e.msg -proc start*(proving: Proving) = - asyncSpawn proving.run() +proc start*(proving: Proving) {.async.} = + if proving.loop.isSome: + return -proc stop*(proving: Proving) = - proving.stopped = true + proving.loop = some proving.run() + +proc stop*(proving: Proving) {.async.} = + if loop =? proving.loop: + proving.loop = Future[void].none + if not loop.finished: + await loop.cancelAndWait() proc submitProof*(proving: Proving, id: ContractId, proof: seq[byte]) {.async.} = await proving.proofs.submitProof(id, proof) diff --git a/tests/dagger/testproving.nim b/tests/dagger/testproving.nim index 159fb732..29e000f7 100644 --- a/tests/dagger/testproving.nim +++ b/tests/dagger/testproving.nim @@ -13,10 +13,10 @@ suite "Proving": setup: proofs = MockProofs.new() proving = Proving.new(proofs) - proving.start() + await proving.start() teardown: - proving.stop() + await proving.stop() proc advanceToNextPeriod(proofs: MockProofs) {.async.} = let current = await proofs.getCurrentPeriod()