123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- package fsm
- import (
- "context"
- "time"
- )
- type Hook[K comparable, EV any] func(ctx context.Context, event Event[K, EV]) error
- type State[SK, EK comparable, EV any] interface {
- Name() SK
- SetAfterEnter([]Hook[EK, EV])
- AfterEnter() []Hook[EK, EV]
- SetBeforeLeave([]Hook[EK, EV])
- BeforeLeave() []Hook[EK, EV]
- }
- type Event[EK comparable, EV any] interface {
- Name() EK
- Data() EV
- }
- type RetryableError interface {
- error
- RetryableError()
- }
- type Transition[SK, EK comparable, EV any] interface {
- SetGuards([]Hook[EK, EV])
- Guards() []Hook[EK, EV]
- SetActions([]Hook[EK, EV])
- Actions() []Hook[EK, EV]
- Next() SK
- }
- type Matrix[SK, EK comparable, EV any] map[SK]map[EK]Transition[SK, EK, EV]
- type BackoffFunc func() time.Duration
- type FSM[SK, EK comparable, EV any] interface {
- Context() context.Context
- Name() string
- SetBackoff(fn BackoffFunc)
-
- SetFeed(feed Feed[SK, EK, EV])
-
- SetMatrix(mx Matrix[SK, EK, EV])
-
-
- SetOnUnavailable(OnError[SK, EK])
-
-
- SetOnGuardFailure(OnError[SK, EK])
-
-
- SetOnActionFailure(OnError[SK, EK])
-
-
- SetOnEnterFailure(OnError[SK, EK])
-
-
- SetOnLeaveFailure(OnError[SK, EK])
- StartState() State[SK, EK, EV]
- EndState() State[SK, EK, EV]
- ErrorState() State[SK, EK, EV]
- }
- type PushMachine[SK, EK comparable, EV any] interface {
- FSM[SK, EK, EV]
- Handle(context.Context, Event[EK, EV]) error
- }
- type PullMachine[SK, EK comparable, EV any] interface {
- FSM[SK, EK, EV]
- Start(ctx context.Context, events chan<- Event[EK, EV]) State[SK, EK, EV]
- }
- var (
- BackoffInitialDelay = time.Millisecond
- BackoffMaxAttempts = 10
- DefaultBackoffAttempts = 0
-
- NoBackoff BackoffFunc = func() time.Duration {
- DefaultBackoffAttempts++
- if DefaultBackoffAttempts > BackoffMaxAttempts {
- return -1
- }
- return YoloBackoff()
- }
-
- ExponentialBackoff BackoffFunc = func() time.Duration {
- d := NoBackoff()
- if d < 0 {
- return d
- }
- return (1 << DefaultBackoffAttempts) * BackoffInitialDelay
- }
-
- YoloBackoff BackoffFunc = func() time.Duration {
- return 0
- }
- )
- type Feed[SK, EK comparable, EV any] func(fsm FSM[SK, EK, EV]) Event[EK, EV]
|