• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 12309399098

13 Dec 2024 04:05AM UTC coverage: 58.649% (+9.7%) from 48.92%
12309399098

Pull #9140

github

starius
docs: add release notes entry
Pull Request #9140: htlcswitch: use fn.GoroutineManager

54 of 81 new or added lines in 2 files covered. (66.67%)

17 existing lines in 4 files now uncovered.

134519 of 229362 relevant lines covered (58.65%)

19214.76 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.39
/protofsm/state_machine.go
1
package protofsm
2

3
import (
4
        "context"
5
        "fmt"
6
        "sync"
7
        "time"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/wire"
12
        "github.com/lightningnetwork/lnd/chainntnfs"
13
        "github.com/lightningnetwork/lnd/fn/v2"
14
        "github.com/lightningnetwork/lnd/lnutils"
15
        "github.com/lightningnetwork/lnd/lnwire"
16
)
17

18
const (
19
        // pollInterval is the interval at which we'll poll the SendWhen
20
        // predicate if specified.
21
        pollInterval = time.Millisecond * 100
22
)
23

24
var (
25
        // ErrStateMachineShutdown occurs when trying to feed an event to a
26
        // StateMachine that has been asked to Stop.
27
        ErrStateMachineShutdown = fmt.Errorf("StateMachine is shutting down")
28

29
        // background is a shortcut for context.Background.
30
        background = context.Background()
31
)
32

33
// EmittedEvent is a special type that can be emitted by a state transition.
34
// This can container internal events which are to be routed back to the state,
35
// or external events which are to be sent to the daemon.
36
type EmittedEvent[Event any] struct {
37
        // InternalEvent is an optional internal event that is to be routed
38
        // back to the target state. This enables state to trigger one or many
39
        // state transitions without a new external event.
40
        InternalEvent []Event
41

42
        // ExternalEvent is an optional external event that is to be sent to
43
        // the daemon for dispatch. Usually, this is some form of I/O.
44
        ExternalEvents DaemonEventSet
45
}
46

47
// StateTransition is a state transition type. It denotes the next state to go
48
// to, and also the set of events to emit.
49
type StateTransition[Event any, Env Environment] struct {
50
        // NextState is the next state to transition to.
51
        NextState State[Event, Env]
52

53
        // NewEvents is the set of events to emit.
54
        NewEvents fn.Option[EmittedEvent[Event]]
55
}
56

57
// Environment is an abstract interface that represents the environment that
58
// the state machine will execute using. From the PoV of the main state machine
59
// executor, we just care about being able to clean up any resources that were
60
// allocated by the environment.
61
type Environment interface {
62
        // Name returns the name of the environment. This is used to uniquely
63
        // identify the environment of related state machines.
64
        Name() string
65
}
66

67
// State defines an abstract state along, namely its state transition function
68
// that takes as input an event and an environment, and returns a state
69
// transition (next state, and set of events to emit). As state can also either
70
// be terminal, or not, a terminal event causes state execution to halt.
71
type State[Event any, Env Environment] interface {
72
        // ProcessEvent takes an event and an environment, and returns a new
73
        // state transition. This will be iteratively called until either a
74
        // terminal state is reached, or no further internal events are
75
        // emitted.
76
        ProcessEvent(event Event, env Env) (*StateTransition[Event, Env], error)
77

78
        // IsTerminal returns true if this state is terminal, and false
79
        // otherwise.
80
        IsTerminal() bool
81

82
        // TODO(roasbeef): also add state serialization?
83
}
84

85
// DaemonAdapters is a set of methods that server as adapters to bridge the
86
// pure world of the FSM to the real world of the daemon. These will be used to
87
// do things like broadcast transactions, or send messages to peers.
88
type DaemonAdapters interface {
89
        // SendMessages sends the target set of messages to the target peer.
90
        SendMessages(btcec.PublicKey, []lnwire.Message) error
91

92
        // BroadcastTransaction broadcasts a transaction with the target label.
93
        BroadcastTransaction(*wire.MsgTx, string) error
94

95
        // RegisterConfirmationsNtfn registers an intent to be notified once
96
        // txid reaches numConfs confirmations. We also pass in the pkScript as
97
        // the default light client instead needs to match on scripts created
98
        // in the block. If a nil txid is passed in, then not only should we
99
        // match on the script, but we should also dispatch once the
100
        // transaction containing the script reaches numConfs confirmations.
101
        // This can be useful in instances where we only know the script in
102
        // advance, but not the transaction containing it.
103
        //
104
        // TODO(roasbeef): could abstract further?
105
        RegisterConfirmationsNtfn(txid *chainhash.Hash, pkScript []byte,
106
                numConfs, heightHint uint32,
107
                opts ...chainntnfs.NotifierOption,
108
        ) (*chainntnfs.ConfirmationEvent, error)
109

110
        // RegisterSpendNtfn registers an intent to be notified once the target
111
        // outpoint is successfully spent within a transaction. The script that
112
        // the outpoint creates must also be specified. This allows this
113
        // interface to be implemented by BIP 158-like filtering.
114
        RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript []byte,
115
                heightHint uint32) (*chainntnfs.SpendEvent, error)
116
}
117

118
// stateQuery is used by outside callers to query the internal state of the
119
// state machine.
120
type stateQuery[Event any, Env Environment] struct {
121
        // CurrentState is a channel that will be sent the current state of the
122
        // state machine.
123
        CurrentState chan State[Event, Env]
124
}
125

126
// StateMachine represents an abstract FSM that is able to process new incoming
127
// events and drive a state machine to termination. This implementation uses
128
// type params to abstract over the types of events and environment. Events
129
// trigger new state transitions, that use the environment to perform some
130
// action.
131
//
132
// TODO(roasbeef): terminal check, daemon event execution, init?
133
type StateMachine[Event any, Env Environment] struct {
134
        cfg StateMachineCfg[Event, Env]
135

136
        // events is the channel that will be used to send new events to the
137
        // FSM.
138
        events chan Event
139

140
        // newStateEvents is an EventDistributor that will be used to notify
141
        // any relevant callers of new state transitions that occur.
142
        newStateEvents *fn.EventDistributor[State[Event, Env]]
143

144
        // stateQuery is a channel that will be used by outside callers to
145
        // query the internal state machine state.
146
        stateQuery chan stateQuery[Event, Env]
147

148
        wg   fn.GoroutineManager
149
        quit chan struct{}
150

151
        startOnce sync.Once
152
        stopOnce  sync.Once
153
}
154

155
// ErrorReporter is an interface that's used to report errors that occur during
156
// state machine execution.
157
type ErrorReporter interface {
158
        // ReportError is a method that's used to report an error that occurred
159
        // during state machine execution.
160
        ReportError(err error)
161
}
162

163
// StateMachineCfg is a configuration struct that's used to create a new state
164
// machine.
165
type StateMachineCfg[Event any, Env Environment] struct {
166
        // ErrorReporter is used to report errors that occur during state
167
        // transitions.
168
        ErrorReporter ErrorReporter
169

170
        // Daemon is a set of adapters that will be used to bridge the FSM to
171
        // the daemon.
172
        Daemon DaemonAdapters
173

174
        // InitialState is the initial state of the state machine.
175
        InitialState State[Event, Env]
176

177
        // Env is the environment that the state machine will use to execute.
178
        Env Env
179

180
        // InitEvent is an optional event that will be sent to the state
181
        // machine as if it was emitted at the onset of the state machine. This
182
        // can be used to set up tracking state such as a txid confirmation
183
        // event.
184
        InitEvent fn.Option[DaemonEvent]
185

186
        // MsgMapper is an optional message mapper that can be used to map
187
        // normal wire messages into FSM events.
188
        MsgMapper fn.Option[MsgMapper[Event]]
189

190
        // CustomPollInterval is an optional custom poll interval that can be
191
        // used to set a quicker interval for tests.
192
        CustomPollInterval fn.Option[time.Duration]
193
}
194

195
// NewStateMachine creates a new state machine given a set of daemon adapters,
196
// an initial state, an environment, and an event to process as if emitted at
197
// the onset of the state machine. Such an event can be used to set up tracking
198
// state such as a txid confirmation event.
199
func NewStateMachine[Event any, Env Environment](cfg StateMachineCfg[Event, Env], //nolint:ll
200
) StateMachine[Event, Env] {
28✔
201

28✔
202
        return StateMachine[Event, Env]{
28✔
203
                cfg:            cfg,
28✔
204
                events:         make(chan Event, 1),
28✔
205
                stateQuery:     make(chan stateQuery[Event, Env]),
28✔
206
                wg:             *fn.NewGoroutineManager(),
28✔
207
                newStateEvents: fn.NewEventDistributor[State[Event, Env]](),
28✔
208
                quit:           make(chan struct{}),
28✔
209
        }
28✔
210
}
28✔
211

212
// Start starts the state machine. This will spawn a goroutine that will drive
213
// the state machine to completion.
214
func (s *StateMachine[Event, Env]) Start() {
28✔
215
        s.startOnce.Do(func() {
56✔
216
                _ = s.wg.Go(background, func(ctx context.Context) {
56✔
217
                        s.driveMachine()
28✔
218
                })
28✔
219
        })
220
}
221

222
// Stop stops the state machine. This will block until the state machine has
223
// reached a stopping point.
224
func (s *StateMachine[Event, Env]) Stop() {
37✔
225
        s.stopOnce.Do(func() {
65✔
226
                close(s.quit)
28✔
227
                s.wg.Stop()
28✔
228
        })
28✔
229
}
230

231
// SendEvent sends a new event to the state machine.
232
//
233
// TODO(roasbeef): bool if processed?
234
func (s *StateMachine[Event, Env]) SendEvent(event Event) {
38✔
235
        log.Debugf("FSM(%v): sending event: %v", s.cfg.Env.Name(),
38✔
236
                lnutils.SpewLogClosure(event),
38✔
237
        )
38✔
238

38✔
239
        select {
38✔
240
        case s.events <- event:
38✔
241
        case <-s.quit:
×
242
                return
×
243
        }
244
}
245

246
// CanHandle returns true if the target message can be routed to the state
247
// machine.
248
func (s *StateMachine[Event, Env]) CanHandle(msg lnwire.Message) bool {
2✔
249
        cfgMapper := s.cfg.MsgMapper
2✔
250
        return fn.MapOptionZ(cfgMapper, func(mapper MsgMapper[Event]) bool {
4✔
251
                return mapper.MapMsg(msg).IsSome()
2✔
252
        })
2✔
253
}
254

255
// Name returns the name of the state machine's environment.
256
func (s *StateMachine[Event, Env]) Name() string {
×
257
        return s.cfg.Env.Name()
×
258
}
×
259

260
// SendMessage attempts to send a wire message to the state machine. If the
261
// message can be mapped using the default message mapper, then true is
262
// returned indicating that the message was processed. Otherwise, false is
263
// returned.
264
func (s *StateMachine[Event, Env]) SendMessage(msg lnwire.Message) bool {
1✔
265
        // If we have no message mapper, then return false as we can't process
1✔
266
        // this message.
1✔
267
        if !s.cfg.MsgMapper.IsSome() {
1✔
268
                return false
×
269
        }
×
270

271
        log.Debugf("FSM(%v): sending msg: %v", s.cfg.Env.Name(),
1✔
272
                lnutils.SpewLogClosure(msg),
1✔
273
        )
1✔
274

1✔
275
        // Otherwise, try to map the message using the default message mapper.
1✔
276
        // If we can't extract an event, then we'll return false to indicate
1✔
277
        // that the message wasn't processed.
1✔
278
        var processed bool
1✔
279
        s.cfg.MsgMapper.WhenSome(func(mapper MsgMapper[Event]) {
2✔
280
                event := mapper.MapMsg(msg)
1✔
281

1✔
282
                event.WhenSome(func(event Event) {
2✔
283
                        s.SendEvent(event)
1✔
284

1✔
285
                        processed = true
1✔
286
                })
1✔
287
        })
288

289
        return processed
1✔
290
}
291

292
// CurrentState returns the current state of the state machine.
293
func (s *StateMachine[Event, Env]) CurrentState() (State[Event, Env], error) {
17✔
294
        query := stateQuery[Event, Env]{
17✔
295
                CurrentState: make(chan State[Event, Env], 1),
17✔
296
        }
17✔
297

17✔
298
        if !fn.SendOrQuit(s.stateQuery, query, s.quit) {
17✔
299
                return nil, ErrStateMachineShutdown
×
300
        }
×
301

302
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
17✔
303
}
304

305
// StateSubscriber represents an active subscription to be notified of new
306
// state transitions.
307
type StateSubscriber[E any, F Environment] *fn.EventReceiver[State[E, F]]
308

309
// RegisterStateEvents registers a new event listener that will be notified of
310
// new state transitions.
311
func (s *StateMachine[Event, Env]) RegisterStateEvents() StateSubscriber[
312
        Event, Env] {
28✔
313

28✔
314
        subscriber := fn.NewEventReceiver[State[Event, Env]](10)
28✔
315

28✔
316
        // TODO(roasbeef): instead give the state and the input event?
28✔
317

28✔
318
        s.newStateEvents.RegisterSubscriber(subscriber)
28✔
319

28✔
320
        return subscriber
28✔
321
}
28✔
322

323
// RemoveStateSub removes the target state subscriber from the set of active
324
// subscribers.
325
func (s *StateMachine[Event, Env]) RemoveStateSub(sub StateSubscriber[
326
        Event, Env]) {
28✔
327

28✔
328
        _ = s.newStateEvents.RemoveSubscriber(sub)
28✔
329
}
28✔
330

331
// executeDaemonEvent executes a daemon event, which is a special type of event
332
// that can be emitted as part of the state transition function of the state
333
// machine. An error is returned if the type of event is unknown.
334
//
335
//nolint:funlen
336
func (s *StateMachine[Event, Env]) executeDaemonEvent(
337
        event DaemonEvent) error {
47✔
338

47✔
339
        switch daemonEvent := event.(type) {
47✔
340
        // This is a send message event, so we'll send the event, and also mind
341
        // any preconditions as well as post-send events.
342
        case *SendMsgEvent[Event]:
17✔
343
                sendAndCleanUp := func() error {
33✔
344
                        log.Debugf("FSM(%v): sending message to target(%x): "+
16✔
345
                                "%v", s.cfg.Env.Name(),
16✔
346
                                daemonEvent.TargetPeer.SerializeCompressed(),
16✔
347
                                lnutils.SpewLogClosure(daemonEvent.Msgs),
16✔
348
                        )
16✔
349

16✔
350
                        err := s.cfg.Daemon.SendMessages(
16✔
351
                                daemonEvent.TargetPeer, daemonEvent.Msgs,
16✔
352
                        )
16✔
353
                        if err != nil {
16✔
354
                                return fmt.Errorf("unable to send msgs: %w",
×
355
                                        err)
×
356
                        }
×
357

358
                        // If a post-send event was specified, then we'll funnel
359
                        // that back into the main state machine now as well.
360
                        return fn.MapOptionZ(daemonEvent.PostSendEvent, func(event Event) error { //nolint:ll
19✔
361
                                launched := s.wg.Go(
3✔
362
                                        background, func(ctx context.Context) {
6✔
363
                                                log.Debugf("FSM(%v): sending "+
3✔
364
                                                        "post-send event: %v",
3✔
365
                                                        s.cfg.Env.Name(),
3✔
366
                                                        lnutils.SpewLogClosure(
3✔
367
                                                                event,
3✔
368
                                                        ),
3✔
369
                                                )
3✔
370

3✔
371
                                                s.SendEvent(event)
3✔
372
                                        },
3✔
373
                                )
374

375
                                if !launched {
3✔
376
                                        return ErrStateMachineShutdown
×
377
                                }
×
378

379
                                return nil
3✔
380
                        })
381
                }
382

383
                // If this doesn't have a SendWhen predicate, then we can just
384
                // send it off right away.
385
                if !daemonEvent.SendWhen.IsSome() {
29✔
386
                        return sendAndCleanUp()
12✔
387
                }
12✔
388

389
                // Otherwise, this has a SendWhen predicate, so we'll need
390
                // launch a goroutine to poll the SendWhen, then send only once
391
                // the predicate is true.
392
                launched := s.wg.Go(background, func(ctx context.Context) {
10✔
393
                        predicateTicker := time.NewTicker(
5✔
394
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
5✔
395
                        )
5✔
396
                        defer predicateTicker.Stop()
5✔
397

5✔
398
                        log.Infof("FSM(%v): waiting for send predicate to "+
5✔
399
                                "be true", s.cfg.Env.Name())
5✔
400

5✔
401
                        for {
12✔
402
                                select {
7✔
403
                                case <-predicateTicker.C:
6✔
404
                                        canSend := fn.MapOptionZ(
6✔
405
                                                daemonEvent.SendWhen,
6✔
406
                                                func(pred SendPredicate) bool {
12✔
407
                                                        return pred()
6✔
408
                                                },
6✔
409
                                        )
410

411
                                        if canSend {
10✔
412
                                                log.Infof("FSM(%v): send "+
4✔
413
                                                        "active predicate",
4✔
414
                                                        s.cfg.Env.Name())
4✔
415

4✔
416
                                                err := sendAndCleanUp()
4✔
417
                                                if err != nil {
4✔
418
                                                        //nolint:ll
×
419
                                                        log.Errorf("FSM(%v): unable to send message: %v", err)
×
420
                                                }
×
421

422
                                                return
4✔
423
                                        }
424

425
                                case <-ctx.Done():
1✔
426
                                        return
1✔
427
                                }
428
                        }
429
                })
430

431
                if !launched {
5✔
432
                        return ErrStateMachineShutdown
×
433
                }
×
434

435
                return nil
5✔
436

437
        // If this is a broadcast transaction event, then we'll broadcast with
438
        // the label attached.
439
        case *BroadcastTxn:
6✔
440
                log.Debugf("FSM(%v): broadcasting txn, txid=%v",
6✔
441
                        s.cfg.Env.Name(), daemonEvent.Tx.TxHash())
6✔
442

6✔
443
                err := s.cfg.Daemon.BroadcastTransaction(
6✔
444
                        daemonEvent.Tx, daemonEvent.Label,
6✔
445
                )
6✔
446
                if err != nil {
6✔
447
                        return fmt.Errorf("unable to broadcast txn: %w", err)
×
448
                }
×
449

450
                return nil
6✔
451

452
        // The state machine has requested a new event to be sent once a
453
        // transaction spending a specified outpoint has confirmed.
454
        case *RegisterSpend[Event]:
24✔
455
                log.Debugf("FSM(%v): registering spend: %v", s.cfg.Env.Name(),
24✔
456
                        daemonEvent.OutPoint)
24✔
457

24✔
458
                spendEvent, err := s.cfg.Daemon.RegisterSpendNtfn(
24✔
459
                        &daemonEvent.OutPoint, daemonEvent.PkScript,
24✔
460
                        daemonEvent.HeightHint,
24✔
461
                )
24✔
462
                if err != nil {
24✔
463
                        return fmt.Errorf("unable to register spend: %w", err)
×
464
                }
×
465

466
                launched := s.wg.Go(background, func(ctx context.Context) {
48✔
467
                        for {
48✔
468
                                select {
24✔
469
                                case spend, ok := <-spendEvent.Spend:
×
470
                                        if !ok {
×
471
                                                return
×
472
                                        }
×
473

474
                                        // If there's a post-send event, then
475
                                        // we'll send that into the current
476
                                        // state now.
477
                                        postSpend := daemonEvent.PostSpendEvent
×
478
                                        postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:ll
×
479
                                                customEvent := f(spend)
×
480
                                                s.SendEvent(customEvent)
×
481
                                        })
×
482

483
                                        return
×
484

485
                                case <-ctx.Done():
24✔
486
                                        return
24✔
487
                                }
488
                        }
489
                })
490

491
                if !launched {
24✔
492
                        return ErrStateMachineShutdown
×
493
                }
×
494

495
                return nil
24✔
496

497
        // The state machine has requested a new event to be sent once a
498
        // specified txid+pkScript pair has confirmed.
499
        case *RegisterConf[Event]:
×
500
                log.Debugf("FSM(%v): registering conf: %v", s.cfg.Env.Name(),
×
501
                        daemonEvent.Txid)
×
502

×
503
                numConfs := daemonEvent.NumConfs.UnwrapOr(1)
×
504
                confEvent, err := s.cfg.Daemon.RegisterConfirmationsNtfn(
×
505
                        &daemonEvent.Txid, daemonEvent.PkScript,
×
506
                        numConfs, daemonEvent.HeightHint,
×
507
                )
×
508
                if err != nil {
×
509
                        return fmt.Errorf("unable to register conf: %w", err)
×
510
                }
×
511

NEW
512
                launched := s.wg.Go(background, func(ctx context.Context) {
×
513
                        for {
×
514
                                select {
×
515
                                case <-confEvent.Confirmed:
×
516
                                        // If there's a post-conf event, then
×
517
                                        // we'll send that into the current
×
518
                                        // state now.
×
519
                                        //
×
520
                                        // TODO(roasbeef): refactor to
×
521
                                        // dispatchAfterRecv w/ above
×
522
                                        postConf := daemonEvent.PostConfEvent
×
523
                                        postConf.WhenSome(func(e Event) {
×
524
                                                s.SendEvent(e)
×
525
                                        })
×
526

527
                                        return
×
528

529
                                case <-ctx.Done():
×
530
                                        return
×
531
                                }
532
                        }
533
                })
534

535
                if !launched {
×
536
                        return ErrStateMachineShutdown
×
537
                }
×
538

539
                return nil
×
540
        }
541

542
        return fmt.Errorf("unknown daemon event: %T", event)
×
543
}
544

545
// applyEvents applies a new event to the state machine. This will continue
546
// until no further events are emitted by the state machine. Along the way,
547
// we'll also ensure to execute any daemon events that are emitted.
548
func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
549
        newEvent Event) (State[Event, Env], error) {
38✔
550

38✔
551
        log.Debugf("FSM(%v): applying new event", s.cfg.Env.Name(),
38✔
552
                lnutils.SpewLogClosure(newEvent),
38✔
553
        )
38✔
554
        eventQueue := fn.NewQueue(newEvent)
38✔
555

38✔
556
        // Given the next event to handle, we'll process the event, then add
38✔
557
        // any new emitted internal events to our event queue. This continues
38✔
558
        // until we reach a terminal state, or we run out of internal events to
38✔
559
        // process.
38✔
560
        //
38✔
561
        //nolint:ll
38✔
562
        for nextEvent := eventQueue.Dequeue(); nextEvent.IsSome(); nextEvent = eventQueue.Dequeue() {
84✔
563
                err := fn.MapOptionZ(nextEvent, func(event Event) error {
92✔
564
                        log.Debugf("FSM(%v): processing event: %v",
46✔
565
                                s.cfg.Env.Name(),
46✔
566
                                lnutils.SpewLogClosure(event),
46✔
567
                        )
46✔
568

46✔
569
                        // Apply the state transition function of the current
46✔
570
                        // state given this new event and our existing env.
46✔
571
                        transition, err := currentState.ProcessEvent(
46✔
572
                                event, s.cfg.Env,
46✔
573
                        )
46✔
574
                        if err != nil {
55✔
575
                                return err
9✔
576
                        }
9✔
577

578
                        newEvents := transition.NewEvents
37✔
579
                        err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll
63✔
580
                                // With the event processed, we'll process any
26✔
581
                                // new daemon events that were emitted as part
26✔
582
                                // of this new state transition.
26✔
583
                                for _, dEvent := range events.ExternalEvents {
48✔
584
                                        err := s.executeDaemonEvent(
22✔
585
                                                dEvent,
22✔
586
                                        )
22✔
587
                                        if err != nil {
22✔
588
                                                return err
×
589
                                        }
×
590
                                }
591

592
                                // Next, we'll add any new emitted events to our
593
                                // event queue.
594
                                //
595
                                //nolint:ll
596
                                for _, inEvent := range events.InternalEvent {
34✔
597
                                        log.Debugf("FSM(%v): adding "+
8✔
598
                                                "new internal event "+
8✔
599
                                                "to queue: %v",
8✔
600
                                                s.cfg.Env.Name(),
8✔
601
                                                lnutils.SpewLogClosure(
8✔
602
                                                        inEvent,
8✔
603
                                                ),
8✔
604
                                        )
8✔
605

8✔
606
                                        eventQueue.Enqueue(inEvent)
8✔
607
                                }
8✔
608

609
                                return nil
26✔
610
                        })
611
                        if err != nil {
37✔
612
                                return err
×
613
                        }
×
614

615
                        log.Infof("FSM(%v): state transition: from_state=%T, "+
37✔
616
                                "to_state=%T",
37✔
617
                                s.cfg.Env.Name(), currentState,
37✔
618
                                transition.NextState)
37✔
619

37✔
620
                        // With our events processed, we'll now update our
37✔
621
                        // internal state.
37✔
622
                        currentState = transition.NextState
37✔
623

37✔
624
                        // Notify our subscribers of the new state transition.
37✔
625
                        //
37✔
626
                        // TODO(roasbeef): will only give us the outer state?
37✔
627
                        //  * let FSMs choose which state to emit?
37✔
628
                        s.newStateEvents.NotifySubscribers(currentState)
37✔
629

37✔
630
                        return nil
37✔
631
                })
632
                if err != nil {
55✔
633
                        return currentState, err
9✔
634
                }
9✔
635
        }
636

637
        return currentState, nil
29✔
638
}
639

640
// driveMachine is the main event loop of the state machine. It accepts any new
641
// incoming events, and then drives the state machine forward until it reaches
642
// a terminal state.
643
func (s *StateMachine[Event, Env]) driveMachine() {
28✔
644
        log.Debugf("FSM(%v): starting state machine", s.cfg.Env.Name())
28✔
645

28✔
646
        currentState := s.cfg.InitialState
28✔
647

28✔
648
        // Before we start, if we have an init daemon event specified, then
28✔
649
        // we'll handle that now.
28✔
650
        err := fn.MapOptionZ(s.cfg.InitEvent, func(event DaemonEvent) error {
53✔
651
                return s.executeDaemonEvent(event)
25✔
652
        })
25✔
653
        if err != nil {
28✔
654
                log.Errorf("unable to execute init event: %w", err)
×
655
                return
×
656
        }
×
657

658
        // We just started driving the state machine, so we'll notify our
659
        // subscribers of this starting state.
660
        s.newStateEvents.NotifySubscribers(currentState)
28✔
661

28✔
662
        for {
102✔
663
                select {
74✔
664
                // We have a new external event, so we'll drive the state
665
                // machine forward until we either run out of internal events,
666
                // or we reach a terminal state.
667
                case newEvent := <-s.events:
38✔
668
                        newState, err := s.applyEvents(currentState, newEvent)
38✔
669
                        if err != nil {
47✔
670
                                s.cfg.ErrorReporter.ReportError(err)
9✔
671

9✔
672
                                log.Errorf("unable to apply event: %v", err)
9✔
673

9✔
674
                                // An error occurred, so we'll tear down the
9✔
675
                                // entire state machine as we can't proceed.
9✔
676
                                go s.Stop()
9✔
677

9✔
678
                                return
9✔
679
                        }
9✔
680

681
                        currentState = newState
29✔
682

683
                // An outside caller is querying our state, so we'll return the
684
                // latest state.
685
                case stateQuery := <-s.stateQuery:
17✔
686
                        if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:ll
17✔
687
                                return
×
688
                        }
×
689

690
                case <-s.wg.Done():
19✔
691
                        return
19✔
692
                }
693
        }
694
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc