lnd/actor/func_actor.go
Olaoluwa Osuntokun b055af6420
actor: add fundamental interfaces and concrete Actor impl
In this commit, we add the actual Actor implementation. We define a
series of types and interfaces, that in concert, describe our actor. An
actor has some ID, a reference (used to send messages to it), and also a
set of defined messages that it'll accept.

An actor can be implemented using a simple function if it's stateless.
Otherwise, a struct can implement the Receive method, and handle its
internal message passing and state that way.
2026-02-06 19:26:54 -08:00

45 lines
1.2 KiB
Go

package actor
import (
"context"
"github.com/lightningnetwork/lnd/fn/v2"
)
// ActorFunc is a function type that represents an actor which functions purely
// based on a simple function processor.
type ActorFunc[M Message, R any] func(context.Context, M) fn.Result[R]
// FunctionBehavior adapts a function to the ActorBehavior interface.
type FunctionBehavior[M Message, R any] struct {
fn ActorFunc[M, R]
}
// NewFunctionBehavior creates a behavior from a function.
func NewFunctionBehavior[M Message, R any](
fn ActorFunc[M, R]) *FunctionBehavior[M, R] {
return &FunctionBehavior[M, R]{fn: fn}
}
// Receive implements ActorBehavior interface for the function.
//
// TODO(roasbeef): just base it off the function direct instead?
func (b *FunctionBehavior[M, R]) Receive(ctx context.Context,
msg M) fn.Result[R] {
return b.fn(ctx, msg)
}
// FunctionBehaviorFromSimple adapts a simpler function to the ActorBehavior
// interface.
func FunctionBehaviorFromSimple[M Message, R any](
sFunc func(M) (R, error)) *FunctionBehavior[M, R] {
return NewFunctionBehavior(
func(ctx context.Context, msg M) fn.Result[R] {
val, err := sFunc(msg)
return fn.NewResult(val, err)
},
)
}