Skip to content

Commit

Permalink
protofsm: add ErrorReporter interface
Browse files Browse the repository at this point in the history
We'll use this to be able to signal to a caller that a critical error
occurred during the state transition.
  • Loading branch information
Roasbeef committed Aug 16, 2024
1 parent cd26a48 commit 12e9e07
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions protofsm/state_machine.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,21 @@ type StateMachine[Event any, Env Environment] struct {
wg sync.WaitGroup
}

// ErrorReporter is an interface that's used to report errors that occur during
// state machine execution.
type ErrorReporter interface {
// ReportError is a method that's used to report an error that occurred
// during state machine execution.
ReportError(err error)
}

// StateMachineCfg is a configuration struct that's used to create a new state
// machine.
type StateMachineCfg[Event any, Env Environment] struct {
// ErrorReporter is used to report errors that occur during state
// transitions.
ErrorReporter ErrorReporter

// Daemon is a set of adapters that will be used to bridge the FSM to
// the daemon.
Daemon DaemonAdapters
Expand Down Expand Up @@ -516,7 +528,7 @@ func (s *StateMachine[Event, Env]) executeDaemonEvent( //nolint:funlen
func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
newEvent Event) (State[Event, Env], error) {

log.Debugf("FSM(%v): applying new event", s.cfg.Env.Name(),
log.Debugf("FSM(%v): applying new event: %v", s.cfg.Env.Name(),
newLogClosure(func() string {
return spew.Sdump(newEvent)
}),
Expand Down Expand Up @@ -599,6 +611,11 @@ func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
return err
}

log.Infof("FSM(%v): state transition: from_state=%T, "+
"to_state=%T",
s.cfg.Env.Name(), currentState,
transition.NextState)

// With our events processed, we'll now update our
// internal state.
currentState = transition.NextState
Expand Down Expand Up @@ -651,9 +668,15 @@ func (s *StateMachine[Event, Env]) driveMachine() {
case newEvent := <-s.events:
newState, err := s.applyEvents(currentState, newEvent)
if err != nil {
// TODO(roasbeef): hard error?
s.cfg.ErrorReporter.ReportError(err)

log.Errorf("unable to apply event: %v", err)
continue

// An error occurred, so we'll tear down the
// entire state machine as we can't proceed.
go s.Stop()

return
}

currentState = newState
Expand Down

0 comments on commit 12e9e07

Please sign in to comment.