Stateful event driven architecture
Recently whilst working on a project I ran into an issue with conflicting requirements. I was dealing with a real-time system that needed to perform logic based on the state/mode that the software system.
The software needed to have various different states and in those various states the system would allow or disallow certain actions and control various actuators. The system also had to keep track of when various asynchronous operations would end and stay responsive in the meantime. This system would also be controlled by a remote application and its specific purpose was managing several pieces of hardware.
This system required a high level of asynchronicity whilst also having to be stateful.
Overview
If we draw a quick overview of the system it would look as the following:
I had already decided to go with an Even Driven Architecture (EDA) since the communication with the remote application could effectively be converted to events. Since the remote application was control software. We could treat the commands it would send us as separate events and respond appropiately.
First design
Deciding to go with an Event Driven Architecture would allow me to split up the system in separate components that would run asynchronously and be responsible for their own external component. Here is diagram show casing what I mean:
This system architecture separates the communication with the remote application from the managing of the hardware. There is still a major issue with this architecture. How do we keep track of state? We should not keep track of the state in the mediator as we might add more mediators for different types of connections or clients.
Second design
The most logical way to solve the issue of the first design is to add a new component that is responsible for managing state. This centralized component would be in charge of filtering out invalid messages from the Mediator and forwarding the appropriate Events to the different Device components. It would look like this:
We added this Event Broker component which has an internal State Machine (that uses the State design pattern). This internal State Machine determines what is and is not allowed in the current mode/state of the system. It then forwards Events using a Generic Observer to the Event Handlers which will react to the events and manage the devices appropiately.