r/mit6824clojure • u/ErnestoGarciaGarcia • Aug 24 '20
Best practices to implement a machine?
I have implemented Raft 2A, until the point where tests are running correctly.
I have intentionally approached the implementation naively, which means that, as I was adding features, I was just:
Adding fields to the main Raft data structure (a map or record in Clojure),
Adding or extending the functions that react to incoming messages, responses and timers by operating on this plain data structure.
I have experienced issues as the program grew, especially regarding the behavior of timers (starting, cancelling, resuming, etc, from many points of the code), to the point that I had to correct many bugs for the tests to run ok, and it is still difficult to reason from the code whether the implementation is correct.
From this, I would like to redo/refactor into an approach where:
Features can be added in a more composable way, so that the correctness of every feature of the Raft algorithm can be reasoned separately, and adding or modifying features does not involve touching others.
Make the implementation automatically testable with different concurrent scenarios, which includes abstracting time away.
Is this your experience? Thoughts? Suggestions?
1
u/siclait Aug 27 '20
I tried to reduce my code complexity by having one central event loop per client. The event loop takes an event and the current state and executes a pure function handler. The handler returns the next state and a list of side effects. At the end of the loop, the state is advanced and the side effects are executed. Modifications to the timer are side effects. The timers can only push events onto the event queue.
With this framework, debugging wasn't too bad. I could inspect each (before state, event, after state) triple to verify the logic. The one thing I would like to add is something similar to what you mentioned regarding abstracting time away. I'd like to be able to easily switch from a real clock to an abstract clock that I can advance / rewind one tick at a time. It would be fun to take that version and use it to create an interactive web-based Raft demo.