protofsm: implement the actor.ActorBehavior interface for StateMachine

In this commit, we implement the actor.ActorBehavior interface for
StateMachine. This enables the state machine executor to be registered
as an actor, and have messages be sent to it via a unique ServiceKey
that a concrete instance will set.

(cherry picked from commit ac4bc2392d)
This commit is contained in:
Olaoluwa Osuntokun 2025-05-16 17:23:06 -07:00 committed by github-actions[bot]
parent c92d48896a
commit a3e0dfa9a2
2 changed files with 43 additions and 0 deletions

23
protofsm/actor_wrapper.go Normal file
View file

@ -0,0 +1,23 @@
package protofsm
import (
"fmt"
"github.com/lightningnetwork/lnd/actor"
)
// ActorMessage wraps an Event, in order to create a new message that can be
// used with the actor package.
type ActorMessage[Event any] struct {
actor.BaseMessage
// Event is the event that is being sent to the actor.
Event Event
}
// MessageType returns the type of the message.
//
// NOTE: This implements the actor.Message interface.
func (a ActorMessage[Event]) MessageType() string {
return fmt.Sprintf("ActorMessage(%T)", a.Event)
}

View file

@ -259,6 +259,26 @@ func (s *StateMachine[Event, Env]) SendEvent(ctx context.Context, event Event) {
}
}
// Receive processes a message and returns a Result. The provided context is the
// actor's internal context, which can be used to detect actor shutdown
// requests.
//
// NOTE: This implements the actor.ActorBehavior interface.
func (s *StateMachine[Event, Env]) Receive(ctx context.Context,
e ActorMessage[Event]) fn.Result[bool] {
select {
case s.events <- e.Event:
return fn.Ok(true)
case <-ctx.Done():
return fn.Err[bool](ctx.Err())
case <-s.quit:
return fn.Err[bool](ErrStateMachineShutdown)
}
}
// CanHandle returns true if the target message can be routed to the state
// machine.
func (s *StateMachine[Event, Env]) CanHandle(msg msgmux.PeerMsg) bool {