Skip to content

Commit 9305fd3

Browse files
committed
protofsm: add ErrorReporter interface
We'll use this to be able to signal to a caller that a critical error occurred during the state transition.
1 parent cc78a01 commit 9305fd3

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

protofsm/state_machine.go

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,9 +150,21 @@ type StateMachine[Event any, Env Environment] struct {
150150
wg sync.WaitGroup
151151
}
152152

153+
// ErrorReporter is an interface that's used to report errors that occur during
154+
// state machine execution.
155+
type ErrorReporter interface {
156+
// ReportError is a method that's used to report an error that occurred
157+
// during state machine execution.
158+
ReportError(err error)
159+
}
160+
153161
// StateMachineCfg is a configuration struct that's used to create a new state
154162
// machine.
155163
type StateMachineCfg[Event any, Env Environment] struct {
164+
// ErrorReporter is used to report errors that occur during state
165+
// transitions.
166+
ErrorReporter ErrorReporter
167+
156168
// Daemon is a set of adapters that will be used to bridge the FSM to
157169
// the daemon.
158170
Daemon DaemonAdapters
@@ -516,7 +528,7 @@ func (s *StateMachine[Event, Env]) executeDaemonEvent( //nolint:funlen
516528
func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
517529
newEvent Event) (State[Event, Env], error) {
518530

519-
log.Debugf("FSM(%v): applying new event", s.cfg.Env.Name(),
531+
log.Debugf("FSM(%v): applying new event: %v", s.cfg.Env.Name(),
520532
newLogClosure(func() string {
521533
return spew.Sdump(newEvent)
522534
}),
@@ -599,6 +611,11 @@ func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
599611
return err
600612
}
601613

614+
log.Infof("FSM(%v): state transition: from_state=%T, "+
615+
"to_state=%T",
616+
s.cfg.Env.Name(), currentState,
617+
transition.NextState)
618+
602619
// With our events processed, we'll now update our
603620
// internal state.
604621
currentState = transition.NextState
@@ -651,9 +668,15 @@ func (s *StateMachine[Event, Env]) driveMachine() {
651668
case newEvent := <-s.events:
652669
newState, err := s.applyEvents(currentState, newEvent)
653670
if err != nil {
654-
// TODO(roasbeef): hard error?
671+
s.cfg.ErrorReporter.ReportError(err)
672+
655673
log.Errorf("unable to apply event: %v", err)
656-
continue
674+
675+
// An error occurred, so we'll tear down the
676+
// entire state machine as we can't proceed.
677+
go s.Stop()
678+
679+
return
657680
}
658681

659682
currentState = newState

0 commit comments

Comments
 (0)