Skip to content

Commit ac4bc23

Browse files
committed
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.
1 parent fa2d0f9 commit ac4bc23

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

protofsm/actor_wrapper.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package protofsm
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/lightningnetwork/lnd/actor"
7+
)
8+
9+
// ActorMessage wraps an Event, in order to create a new message that can be
10+
// used with the actor package.
11+
type ActorMessage[Event any] struct {
12+
actor.BaseMessage
13+
14+
// Event is the event that is being sent to the actor.
15+
Event Event
16+
}
17+
18+
// MessageType returns the type of the message.
19+
//
20+
// NOTE: This implements the actor.Message interface.
21+
func (a ActorMessage[Event]) MessageType() string {
22+
return fmt.Sprintf("ActorMessage(%T)", a.Event)
23+
}

protofsm/state_machine.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,26 @@ func (s *StateMachine[Event, Env]) SendEvent(ctx context.Context, event Event) {
259259
}
260260
}
261261

262+
// Receive processes a message and returns a Result. The provided context is the
263+
// actor's internal context, which can be used to detect actor shutdown
264+
// requests.
265+
//
266+
// NOTE: This implements the actor.ActorBehavior interface.
267+
func (s *StateMachine[Event, Env]) Receive(ctx context.Context,
268+
e ActorMessage[Event]) fn.Result[bool] {
269+
270+
select {
271+
case s.events <- e.Event:
272+
return fn.Ok(true)
273+
274+
case <-ctx.Done():
275+
return fn.Err[bool](ctx.Err())
276+
277+
case <-s.quit:
278+
return fn.Err[bool](ErrStateMachineShutdown)
279+
}
280+
}
281+
262282
// CanHandle returns true if the target message can be routed to the state
263283
// machine.
264284
func (s *StateMachine[Event, Env]) CanHandle(msg msgmux.PeerMsg) bool {

0 commit comments

Comments
 (0)