mirror of
https://github.com/codex-storage/nim-codex.git
synced 2025-02-23 10:08:17 +00:00
implements minimal state switching
This commit is contained in:
parent
21c6fc5d09
commit
894cbe4a0b
@ -5,6 +5,13 @@ type
|
||||
AsyncStateMachine* = ref object of RootObj
|
||||
AsyncState* = ref object of RootObj
|
||||
|
||||
method start*(stateMachine: AsyncStateMachine, initialState: AsyncState) =
|
||||
method run*(state: AsyncState): Future[?AsyncState] {.base.} =
|
||||
discard
|
||||
|
||||
proc runState(state: AsyncState): Future[void] {.async.} =
|
||||
if next =? await state.run():
|
||||
await runState(next)
|
||||
|
||||
proc start*(stateMachine: AsyncStateMachine, initialState: AsyncState) =
|
||||
asyncSpawn runState(initialState)
|
||||
|
||||
|
@ -4,16 +4,27 @@ import pkg/chronos
|
||||
import codex/utils/asyncstatemachine
|
||||
import ../helpers/eventually
|
||||
|
||||
type TestState = ref object of AsyncState
|
||||
type
|
||||
TestState = ref object of AsyncState
|
||||
State1 = ref object of AsyncState
|
||||
State2 = ref object of AsyncState
|
||||
|
||||
var runInvoked = 0
|
||||
var state2runInvoked = 0
|
||||
|
||||
method run(state: TestState): Future[?AsyncState] =
|
||||
method run(state: TestState): Future[?AsyncState] {.async.} =
|
||||
inc runInvoked
|
||||
|
||||
method run(state: State1): Future[?AsyncState] {.async.} =
|
||||
return some AsyncState(State2.new())
|
||||
|
||||
method run(state: State2): Future[?AsyncState] {.async.} =
|
||||
inc state2runInvoked
|
||||
|
||||
suite "async state machines":
|
||||
setup:
|
||||
runInvoked = 0
|
||||
state2runInvoked = 0
|
||||
|
||||
test "creates async state machine":
|
||||
let sm = AsyncStateMachine.new()
|
||||
@ -27,3 +38,12 @@ suite "async state machines":
|
||||
|
||||
check eventually runInvoked == 1
|
||||
|
||||
test "moves to next state when run completes":
|
||||
let sm = AsyncStateMachine.new()
|
||||
let state1 = State1.new()
|
||||
let state2 = State2.new()
|
||||
|
||||
sm.start(state1)
|
||||
|
||||
check eventually state2runInvoked == 1
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user