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

lightningnetwork / lnd / 12301186252

12 Dec 2024 05:01PM UTC coverage: 48.92% (-9.7%) from 58.642%
12301186252

push

github

web-flow
Merge pull request #9309 from yyforyongyu/fix-unit-test

chainntnfs: fix `TestHistoricalConfDetailsTxIndex`

99121 of 202617 relevant lines covered (48.92%)

1.54 hits per line

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

0.0
/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

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

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

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

50
        // NewEvents is the set of events to emit.
51
        NewEvents fn.Option[EmittedEvent[Event]]
52
}
53

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

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

75
        // IsTerminal returns true if this state is terminal, and false
76
        // otherwise.
77
        IsTerminal() bool
78

79
        // TODO(roasbeef): also add state serialization?
80
}
81

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

89
        // BroadcastTransaction broadcasts a transaction with the target label.
90
        BroadcastTransaction(*wire.MsgTx, string) error
91

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

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

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

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

133
        // events is the channel that will be used to send new events to the
134
        // FSM.
135
        events chan Event
136

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

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

145
        wg   fn.GoroutineManager
146
        quit chan struct{}
147

148
        startOnce sync.Once
149
        stopOnce  sync.Once
150
}
151

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

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

167
        // Daemon is a set of adapters that will be used to bridge the FSM to
168
        // the daemon.
169
        Daemon DaemonAdapters
170

171
        // InitialState is the initial state of the state machine.
172
        InitialState State[Event, Env]
173

174
        // Env is the environment that the state machine will use to execute.
175
        Env Env
176

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

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

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

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

×
199
        return StateMachine[Event, Env]{
×
200
                cfg:            cfg,
×
201
                events:         make(chan Event, 1),
×
202
                stateQuery:     make(chan stateQuery[Event, Env]),
×
203
                wg:             *fn.NewGoroutineManager(context.Background()),
×
204
                newStateEvents: fn.NewEventDistributor[State[Event, Env]](),
×
205
                quit:           make(chan struct{}),
×
206
        }
×
207
}
×
208

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

219
// Stop stops the state machine. This will block until the state machine has
220
// reached a stopping point.
221
func (s *StateMachine[Event, Env]) Stop() {
×
222
        s.stopOnce.Do(func() {
×
223
                close(s.quit)
×
224
                s.wg.Stop()
×
225
        })
×
226
}
227

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

×
236
        select {
×
237
        case s.events <- event:
×
238
        case <-s.quit:
×
239
                return
×
240
        }
241
}
242

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

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

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

268
        log.Debugf("FSM(%v): sending msg: %v", s.cfg.Env.Name(),
×
269
                lnutils.SpewLogClosure(msg),
×
270
        )
×
271

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

×
279
                event.WhenSome(func(event Event) {
×
280
                        s.SendEvent(event)
×
281

×
282
                        processed = true
×
283
                })
×
284
        })
285

286
        return processed
×
287
}
288

289
// CurrentState returns the current state of the state machine.
290
func (s *StateMachine[Event, Env]) CurrentState() (State[Event, Env], error) {
×
291
        query := stateQuery[Event, Env]{
×
292
                CurrentState: make(chan State[Event, Env], 1),
×
293
        }
×
294

×
295
        if !fn.SendOrQuit(s.stateQuery, query, s.quit) {
×
296
                return nil, ErrStateMachineShutdown
×
297
        }
×
298

299
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
×
300
}
301

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

306
// RegisterStateEvents registers a new event listener that will be notified of
307
// new state transitions.
308
func (s *StateMachine[Event, Env]) RegisterStateEvents() StateSubscriber[
309
        Event, Env] {
×
310

×
311
        subscriber := fn.NewEventReceiver[State[Event, Env]](10)
×
312

×
313
        // TODO(roasbeef): instead give the state and the input event?
×
314

×
315
        s.newStateEvents.RegisterSubscriber(subscriber)
×
316

×
317
        return subscriber
×
318
}
×
319

320
// RemoveStateSub removes the target state subscriber from the set of active
321
// subscribers.
322
func (s *StateMachine[Event, Env]) RemoveStateSub(sub StateSubscriber[
323
        Event, Env]) {
×
324

×
325
        _ = s.newStateEvents.RemoveSubscriber(sub)
×
326
}
×
327

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

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

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

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

×
365
                                        s.SendEvent(event)
×
366
                                })
×
367

368
                                if !launched {
×
369
                                        return ErrStateMachineShutdown
×
370
                                }
×
371

372
                                return nil
×
373
                        })
374
                }
375

376
                // If this doesn't have a SendWhen predicate, then we can just
377
                // send it off right away.
378
                if !daemonEvent.SendWhen.IsSome() {
×
379
                        return sendAndCleanUp()
×
380
                }
×
381

382
                // Otherwise, this has a SendWhen predicate, so we'll need
383
                // launch a goroutine to poll the SendWhen, then send only once
384
                // the predicate is true.
385
                launched := s.wg.Go(func(ctx context.Context) {
×
386
                        predicateTicker := time.NewTicker(
×
387
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
×
388
                        )
×
389
                        defer predicateTicker.Stop()
×
390

×
391
                        log.Infof("FSM(%v): waiting for send predicate to "+
×
392
                                "be true", s.cfg.Env.Name())
×
393

×
394
                        for {
×
395
                                select {
×
396
                                case <-predicateTicker.C:
×
397
                                        canSend := fn.MapOptionZ(
×
398
                                                daemonEvent.SendWhen,
×
399
                                                func(pred SendPredicate) bool {
×
400
                                                        return pred()
×
401
                                                },
×
402
                                        )
403

404
                                        if canSend {
×
405
                                                log.Infof("FSM(%v): send "+
×
406
                                                        "active predicate",
×
407
                                                        s.cfg.Env.Name())
×
408

×
409
                                                err := sendAndCleanUp()
×
410
                                                if err != nil {
×
411
                                                        //nolint:ll
×
412
                                                        log.Errorf("FSM(%v): unable to send message: %v", err)
×
413
                                                }
×
414

415
                                                return
×
416
                                        }
417

418
                                case <-ctx.Done():
×
419
                                        return
×
420
                                }
421
                        }
422
                })
423

424
                if !launched {
×
425
                        return ErrStateMachineShutdown
×
426
                }
×
427

428
                return nil
×
429

430
        // If this is a broadcast transaction event, then we'll broadcast with
431
        // the label attached.
432
        case *BroadcastTxn:
×
433
                log.Debugf("FSM(%v): broadcasting txn, txid=%v",
×
434
                        s.cfg.Env.Name(), daemonEvent.Tx.TxHash())
×
435

×
436
                err := s.cfg.Daemon.BroadcastTransaction(
×
437
                        daemonEvent.Tx, daemonEvent.Label,
×
438
                )
×
439
                if err != nil {
×
440
                        return fmt.Errorf("unable to broadcast txn: %w", err)
×
441
                }
×
442

443
                return nil
×
444

445
        // The state machine has requested a new event to be sent once a
446
        // transaction spending a specified outpoint has confirmed.
447
        case *RegisterSpend[Event]:
×
448
                log.Debugf("FSM(%v): registering spend: %v", s.cfg.Env.Name(),
×
449
                        daemonEvent.OutPoint)
×
450

×
451
                spendEvent, err := s.cfg.Daemon.RegisterSpendNtfn(
×
452
                        &daemonEvent.OutPoint, daemonEvent.PkScript,
×
453
                        daemonEvent.HeightHint,
×
454
                )
×
455
                if err != nil {
×
456
                        return fmt.Errorf("unable to register spend: %w", err)
×
457
                }
×
458

459
                launched := s.wg.Go(func(ctx context.Context) {
×
460
                        for {
×
461
                                select {
×
462
                                case spend, ok := <-spendEvent.Spend:
×
463
                                        if !ok {
×
464
                                                return
×
465
                                        }
×
466

467
                                        // If there's a post-send event, then
468
                                        // we'll send that into the current
469
                                        // state now.
470
                                        postSpend := daemonEvent.PostSpendEvent
×
471
                                        postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:ll
×
472
                                                customEvent := f(spend)
×
473
                                                s.SendEvent(customEvent)
×
474
                                        })
×
475

476
                                        return
×
477

478
                                case <-ctx.Done():
×
479
                                        return
×
480
                                }
481
                        }
482
                })
483

484
                if !launched {
×
485
                        return ErrStateMachineShutdown
×
486
                }
×
487

488
                return nil
×
489

490
        // The state machine has requested a new event to be sent once a
491
        // specified txid+pkScript pair has confirmed.
492
        case *RegisterConf[Event]:
×
493
                log.Debugf("FSM(%v): registering conf: %v", s.cfg.Env.Name(),
×
494
                        daemonEvent.Txid)
×
495

×
496
                numConfs := daemonEvent.NumConfs.UnwrapOr(1)
×
497
                confEvent, err := s.cfg.Daemon.RegisterConfirmationsNtfn(
×
498
                        &daemonEvent.Txid, daemonEvent.PkScript,
×
499
                        numConfs, daemonEvent.HeightHint,
×
500
                )
×
501
                if err != nil {
×
502
                        return fmt.Errorf("unable to register conf: %w", err)
×
503
                }
×
504

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

520
                                        return
×
521

522
                                case <-ctx.Done():
×
523
                                        return
×
524
                                }
525
                        }
526
                })
527

528
                if !launched {
×
529
                        return ErrStateMachineShutdown
×
530
                }
×
531

532
                return nil
×
533
        }
534

535
        return fmt.Errorf("unknown daemon event: %T", event)
×
536
}
537

538
// applyEvents applies a new event to the state machine. This will continue
539
// until no further events are emitted by the state machine. Along the way,
540
// we'll also ensure to execute any daemon events that are emitted.
541
func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env],
542
        newEvent Event) (State[Event, Env], error) {
×
543

×
544
        log.Debugf("FSM(%v): applying new event", s.cfg.Env.Name(),
×
545
                lnutils.SpewLogClosure(newEvent),
×
546
        )
×
547
        eventQueue := fn.NewQueue(newEvent)
×
548

×
549
        // Given the next event to handle, we'll process the event, then add
×
550
        // any new emitted internal events to our event queue. This continues
×
551
        // until we reach a terminal state, or we run out of internal events to
×
552
        // process.
×
553
        //
×
554
        //nolint:ll
×
555
        for nextEvent := eventQueue.Dequeue(); nextEvent.IsSome(); nextEvent = eventQueue.Dequeue() {
×
556
                err := fn.MapOptionZ(nextEvent, func(event Event) error {
×
557
                        log.Debugf("FSM(%v): processing event: %v",
×
558
                                s.cfg.Env.Name(),
×
559
                                lnutils.SpewLogClosure(event),
×
560
                        )
×
561

×
562
                        // Apply the state transition function of the current
×
563
                        // state given this new event and our existing env.
×
564
                        transition, err := currentState.ProcessEvent(
×
565
                                event, s.cfg.Env,
×
566
                        )
×
567
                        if err != nil {
×
568
                                return err
×
569
                        }
×
570

571
                        newEvents := transition.NewEvents
×
572
                        err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll
×
573
                                // With the event processed, we'll process any
×
574
                                // new daemon events that were emitted as part
×
575
                                // of this new state transition.
×
576
                                for _, dEvent := range events.ExternalEvents {
×
577
                                        err := s.executeDaemonEvent(
×
578
                                                dEvent,
×
579
                                        )
×
580
                                        if err != nil {
×
581
                                                return err
×
582
                                        }
×
583
                                }
584

585
                                // Next, we'll add any new emitted events to our
586
                                // event queue.
587
                                //
588
                                //nolint:ll
589
                                for _, inEvent := range events.InternalEvent {
×
590
                                        log.Debugf("FSM(%v): adding "+
×
591
                                                "new internal event "+
×
592
                                                "to queue: %v",
×
593
                                                s.cfg.Env.Name(),
×
594
                                                lnutils.SpewLogClosure(
×
595
                                                        inEvent,
×
596
                                                ),
×
597
                                        )
×
598

×
599
                                        eventQueue.Enqueue(inEvent)
×
600
                                }
×
601

602
                                return nil
×
603
                        })
604
                        if err != nil {
×
605
                                return err
×
606
                        }
×
607

608
                        log.Infof("FSM(%v): state transition: from_state=%T, "+
×
609
                                "to_state=%T",
×
610
                                s.cfg.Env.Name(), currentState,
×
611
                                transition.NextState)
×
612

×
613
                        // With our events processed, we'll now update our
×
614
                        // internal state.
×
615
                        currentState = transition.NextState
×
616

×
617
                        // Notify our subscribers of the new state transition.
×
618
                        //
×
619
                        // TODO(roasbeef): will only give us the outer state?
×
620
                        //  * let FSMs choose which state to emit?
×
621
                        s.newStateEvents.NotifySubscribers(currentState)
×
622

×
623
                        return nil
×
624
                })
625
                if err != nil {
×
626
                        return currentState, err
×
627
                }
×
628
        }
629

630
        return currentState, nil
×
631
}
632

633
// driveMachine is the main event loop of the state machine. It accepts any new
634
// incoming events, and then drives the state machine forward until it reaches
635
// a terminal state.
636
func (s *StateMachine[Event, Env]) driveMachine() {
×
637
        log.Debugf("FSM(%v): starting state machine", s.cfg.Env.Name())
×
638

×
639
        currentState := s.cfg.InitialState
×
640

×
641
        // Before we start, if we have an init daemon event specified, then
×
642
        // we'll handle that now.
×
643
        err := fn.MapOptionZ(s.cfg.InitEvent, func(event DaemonEvent) error {
×
644
                return s.executeDaemonEvent(event)
×
645
        })
×
646
        if err != nil {
×
647
                log.Errorf("unable to execute init event: %w", err)
×
648
                return
×
649
        }
×
650

651
        // We just started driving the state machine, so we'll notify our
652
        // subscribers of this starting state.
653
        s.newStateEvents.NotifySubscribers(currentState)
×
654

×
655
        for {
×
656
                select {
×
657
                // We have a new external event, so we'll drive the state
658
                // machine forward until we either run out of internal events,
659
                // or we reach a terminal state.
660
                case newEvent := <-s.events:
×
661
                        newState, err := s.applyEvents(currentState, newEvent)
×
662
                        if err != nil {
×
663
                                s.cfg.ErrorReporter.ReportError(err)
×
664

×
665
                                log.Errorf("unable to apply event: %v", err)
×
666

×
667
                                // An error occurred, so we'll tear down the
×
668
                                // entire state machine as we can't proceed.
×
669
                                go s.Stop()
×
670

×
671
                                return
×
672
                        }
×
673

674
                        currentState = newState
×
675

676
                // An outside caller is querying our state, so we'll return the
677
                // latest state.
678
                case stateQuery := <-s.stateQuery:
×
679
                        if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:ll
×
680
                                return
×
681
                        }
×
682

683
                case <-s.wg.Done():
×
684
                        return
×
685
                }
686
        }
687
}
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