Skip to content

Commit

Permalink
Split Network lifecycle into separate state transitions
Browse files Browse the repository at this point in the history
  • Loading branch information
kmazurek committed Sep 27, 2021
1 parent c5d425c commit b319b73
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
4 changes: 2 additions & 2 deletions tests/test_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async def test_remove(self):
@pytest.mark.asyncio
async def test_remove_when_initialized(self):
network = Network(mock.Mock(), f"192.168.0.0/24", "0xdeadbeef")
with pytest.raises(TransitionNotAllowed, match=".*Can't remove when in initialized.*") as e:
with pytest.raises(TransitionNotAllowed, match=".*Can't stop when in initialized.*") as e:
await network.remove()

@pytest.mark.asyncio
Expand All @@ -141,7 +141,7 @@ async def test_remove_when_removed(self):

await network.remove()

with pytest.raises(TransitionNotAllowed, match=".*Can't remove when in removed.*") as e:
with pytest.raises(TransitionNotAllowed, match=".*Can't stop when in removed.*") as e:
await network.remove()

@pytest.mark.asyncio
Expand Down
20 changes: 11 additions & 9 deletions yapapi/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,17 @@ class NetworkState(StateMachine):
removing = State("removing")
removed = State("removed")

# transitions
add_address = creating.to.itself() | ready.to.itself()
# state-altering transitions (lifecycle)
create = initialized.to(creating)
start = creating.to(ready)
stop = ready.to(removing)
remove = removing.to(removed)

# same-state transitions
add_owner_address = creating.to.itself() | ready.to.itself()
add_node = ready.to.itself()
get_id = creating.to.itself() | ready.to.itself() | removing.to.itself()

# lifecycle
create = initialized.to(creating) | creating.to(ready)
remove = ready.to(removing) | removing.to(removed)


class Network:
"""
Expand Down Expand Up @@ -111,7 +113,7 @@ async def create(
# add requestor's own address to the network
await network.add_owner_address(network.owner_ip)

network._state_machine.create()
network._state_machine.start()
return network

def __init__(
Expand Down Expand Up @@ -223,7 +225,7 @@ async def add_owner_address(self, ip: str):
:param ip: the IP address to assign to the requestor node.
"""
self._state_machine.add_address()
self._state_machine.add_owner_address()
self._ensure_ip_in_network(ip)

async with self._nodes_lock:
Expand Down Expand Up @@ -259,7 +261,7 @@ async def add_node(self, node_id: str, ip: Optional[str] = None) -> Node:

async def remove(self) -> None:
"""Remove this network, terminating any connections it provides."""
self._state_machine.remove()
self._state_machine.stop()
await self._net_api.remove_network(self.network_id)
self._state_machine.remove()

Expand Down

0 comments on commit b319b73

Please sign in to comment.